Course contentsShow
← Java
Lesson 1397 of 2,87031. Streams API: Creation and BasicsFree lesson

Common Terminal Operations: forEach, collect, reduce

Identify the most frequently used terminal operations that produce results or perform side effects.

Common Terminal Operations: forEach, collect, reduce

You'll learn the three most essential terminal operations that produce results or perform actions on streams.

When you've built a stream pipeline with intermediate operations like filter() and map(), you need a way to actually do something with the results. That's where terminal operations come in. Three operations dominate everyday stream processing:

forEach: Perform an Action

forEach() executes a given action for each element in the stream. It's your go-to for side effects like printing, logging, or updating external state. Think of it as the stream version of the enhanced for loop, but powered by the Stream API's internal iteration.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.stream().forEach(name -> System.out.println(name));
// Prints each name on a new line

collect: Gather Results into a Collection

collect() accumulates stream elements into a result container like a List, Set, or Map. It's the workhorse for transforming streams back into concrete collections. This is how you materialize your filtered, mapped, or transformed data.

List<String> upperNames = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());
// Result: ["ALICE", "BOB", "CHARLIE"]

reduce: Combine Elements into a Single Value

reduce() performs a reduction operation, combining all elements into a single result using an associative function. Perfect for summing numbers, finding maximums, or concatenating strings.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
int sum = numbers.stream()
    .reduce(0, (a, b) -> a + b);
// Result: 10

Key Takeaway: forEach() performs actions, collect() gathers elements into collections, and reduce() combines elements into a single value—master these three and you'll handle 90% of stream termination scenarios.