The Plain Picture#
The packing station at the end of the belt: pack into one box, or into labelled boxes by city, or just count items per label, or string them into one line.
The Real Names#
collect(collector) is the flexible terminal operation; java.util.stream.Collectors provides the collectors.
// grouping → map of lists
Map<String, List<String>> byCity = students.stream().collect(
Collectors.groupingBy(
Student::city,
TreeMap::new, // group key, and a sorted map to hold groups
Collectors.mapping(Student::name, Collectors.toList())
)
); // what to keep for each member
// {Bangalore=[Priya, Aisha], Delhi=[Rahul, Meera], Mumbai=[Vikram]}
// grouping → counts
students
.stream()
.collect(Collectors.groupingBy(Student::city, TreeMap::new, Collectors.counting()));
// {Bangalore=2, Delhi=2, Mumbai=1}
// grouping → averages
students
.stream()
.collect(
Collectors.groupingBy(
Student::city,
TreeMap::new,
Collectors.averagingInt(Student::score)
)
);
// {Bangalore=200.0, Delhi=162.5, Mumbai=110.0}
// joining strings
students
.stream()
.map(Student::name)
.collect(Collectors.joining(", ", "[", "]"));
// [Priya, Rahul, Aisha, Vikram, Meera]
// partitioning → exactly two groups: true / false
students
.stream()
.collect(
Collectors.partitioningBy(
s -> s.score() >= 150,
Collectors.mapping(Student::name, Collectors.toList())
)
);
// {false=[Vikram], true=[Priya, Rahul, Aisha, Meera]}(Plain groupingBy(Student::city) uses a HashMap, so the group order is unpredictable — Collections, From the Inside Ch 5. The TreeMap::new
argument above just makes the printed output sorted.)
toMap — and its duplicate-key trap:
students.stream().collect(Collectors.toMap(Student::city, Student::name));
// IllegalStateException: Duplicate key Bangalore (attempted merging values Priya and Aisha)
students
.stream()
.collect(Collectors.toMap(Student::city, Student::score, Integer::max)); // third argument: how to MERGE duplicates
// {Bangalore=200, Delhi=175, Mumbai=110} (the best score per city)Always give toMap a merge function unless keys are guaranteed unique.
The "SQL-like" collectors map directly onto database queries you'll learn in SQL Basics (coming soon): groupingBy ≈ GROUP BY, counting ≈
COUNT(*), averagingInt ≈ AVG(), filter ≈ WHERE, sorted ≈ ORDER BY.
Check yourself
3 questionsWrite a collector for "number of students per score".
Show answerHide answer
Collectors.groupingBy(Student::score, Collectors.counting()).
Why did the first toMap call throw, and how do you fix it?
Show answerHide answer
Two students share the key "Bangalore"; supply a merge function as the third argument (e.g. keep the max, or join the names).
groupingBy vs partitioningBy?
Show answerHide answer
groupingBy creates a group for every distinct key; partitioningBy always splits into exactly two groups, true and false.