Terminal Operations: The Final Result

Terminal Operations: The Final Result in Java: Intermediate operations are Lazy. This means they don't actually do anything until you call a Terminal…

Concept Explanation

Intermediate operations are Lazy. This means they don't actually do anything until you call a Terminal Operation. It's like having workers at an assembly line who only start moving once you pull the "Final Trigger" lever.


Common Terminal Operations

  • .collect(): Turns the stream back into a List, Set, or Map.
  • .forEach(): Performs an action (like print) for every item.
  • .count(): Returns the total number of items.
  • .reduce(): Combines all items into one (e.g., summing all numbers).

Syntax or Core Structure

// Summing numbers using reduce
int sum = numbers.stream()
    .reduce(0, (a, b) -> a + b);

// Check if ANY name starts with 'Z'
boolean hasZ = names.stream()
    .anyMatch(n -> n.startsWith("Z"));

Best Practices

  • Don't Reuse Streams: Once a terminal operation is called, the stream is "consumed" and dead. If you need it again, you must call .stream() again.
  • Keep it Readable: If your stream pipeline is 10 lines long, consider breaking it up or using a helper method.

Practice Exercises

  1. The Matchmaker: Use .allMatch() to check if everyone in a list of User objects is over 18 years old.
  2. The Collector: Convert a list of Strings into a Set using Collectors.toSet(). What happens to duplicate strings?
  3. The Sum of Squares: Given a list of integers, use .map() to square them and .reduce() to find the total sum.