Concept Explanation
Think of a Stream as a Factory Assembly Line.
- The Source: You have a bin full of raw parts (e.g., an
ArrayList). - Intermediate Operations: These are the workers along the line. One worker filters out broken parts. Another worker paints (maps) the parts red. The parts are still moving; they haven't been boxed yet.
- Terminal Operation: The final worker marks the box as "Done" and collects them into a finished product.
Crucially, the assembly line doesn't change the raw parts in the bin — it creates a new result.
Syntax or Core Structure
A stream pipeline has three parts:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> result = names.stream() // 1. Source
.filter(n -> n.startsWith("C")) // 2. Intermediate (Filter)
.map(String::toUpperCase) // 2. Intermediate (Map)
.collect(Collectors.toList()); // 3. Terminal (Finish!)
Common Intermediate Operations
.filter(predicate): Keeps items that match a condition..map(function): Transforms each item into something else..sorted(): Rearranges the items..distinct(): Removes duplicates.
Practice Exercises
- The Filter Challenge: Create a list of numbers. Use a stream to find all numbers greater than 50 and print them.
- The Name Game: Take a list of names, convert them all to lowercase, and then sort them alphabetically.
- Short Circuit: Research
.limit(n). How can you use it to only process the first 3 items of a giant list?