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
- The Matchmaker: Use
.allMatch()to check if everyone in a list ofUserobjects is over 18 years old. - The Collector: Convert a list of Strings into a
SetusingCollectors.toSet(). What happens to duplicate strings? - The Sum of Squares: Given a list of integers, use
.map()to square them and.reduce()to find the total sum.