Advanced Streams & Collectors
Prerequisites: Advanced generics & bounded type parameters
Collectors supports grouping, joining, and building maps directly
from a stream pipeline:
import java.util.stream.Collectors;
record Person(String name, String city) {}
List<Person> people = List.of(
new Person("Ada", "London"),
new Person("Grace", "New York"),
new Person("Al", "London")
);
Map<String, List<Person>> byCity = people.stream()
.collect(Collectors.groupingBy(Person::city));
String names = people.stream()
.map(Person::name)
.collect(Collectors.joining(", "));
// "Ada, Grace, Al"
A .parallelStream() splits work across multiple CPU cores
automatically — useful for large, CPU-bound collections, but adds
overhead that can make it slower for small ones.
Common mistakes
- Reaching for
.parallelStream()by default — measure first; for small collections or I/O-bound work it typically doesn't help.