Course contentsShow
← Java
Lesson 1523 of 2,87033. Streams API: Terminal OperationsFree lesson

Understanding Terminal Operations: count, min, and max

Learn how count, min, and max finalize stream processing and why they're terminal operations that trigger computation.

Understanding Terminal Operations: count, min, and max

You'll learn how three simple terminal operations finalize stream processing by triggering computation and producing single values.

What Makes These Operations Terminal?

Like forEach and collect, the operations count(), min(), and max() are terminal operations—they end the stream pipeline and force all intermediate operations to execute. Think of them as the finish line: once you call them, the race begins and produces a final result.

Until you call a terminal operation, your stream pipeline is just a blueprint. These three methods pull the trigger and actually process your data.

count(): Counting Elements

count() returns the number of elements in the stream as a long:

long count = Stream.of("apple", "banana", "cherry")
    .filter(s -> s.startsWith("a"))
    .count();  // 1

min() and max(): Finding Extremes

Both min() and max() require a Comparator and return an Optional (because the stream might be empty):

Optional<Integer> smallest = Stream.of(5, 2, 8, 1)
    .min(Integer::compareTo);  // Optional[1]

Optional<Integer> largest = Stream.of(5, 2, 8, 1)
    .max(Integer::compareTo);  // Optional[8]

The Optional return type protects you from null values when the stream is empty:

Optional<Integer> empty = Stream.<Integer>empty()
    .max(Integer::compareTo);  // Optional.empty

Why These Are Terminal

All three operations must inspect the stream to produce their answer. They trigger the entire pipeline to execute, consume the stream, and return a concrete value. After calling any of them, the stream is closed and cannot be reused.

Key Takeaway: count(), min(), and max() are terminal operations that trigger stream processing and return final results—a count as long, or an Optional containing the minimum or maximum element based on a Comparator.