A stream pipeline that ends with toList gives you a list. A collector gives you whatever shape the problem needs. It is a map keyed by a field, a nested grouping, a count, a joined string. The method collect takes a collector, and the collectors in java.util.stream.Collectors cover most of the shapes that the real code needs.
The previous lesson in this module covered "Which Intermediate and Terminal Stream Operations Matter Most?", and the next lesson in this module is about "What Do Records and the New switch Forms Simplify?".
What is the difference between collect and toList?
The method toList() is the shorthand. It produces an unmodifiable list in the encounter order of the stream, and that is all it does. The call collect(Collectors.toList()) produces the same thing but it lets you swap in a different list implementation, and it is the only form that works with a downstream collector. The rule is simple. You use toList for a plain list and collect for anything else.
How do you build a map?
The method toMap takes two functions. One of them builds the key, and the other one builds the value. There is a third form for handling the duplicate keys. Without it, two elements that produce the same key make the collector throw, which is a safety net rather than a bug.
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class CollectorsBasics {
record Employee(String name, String team, double salary) { }
public static void main(String[] args) {
List<Employee> staff = List.of(
new Employee("ana", "core", 3000),
new Employee("bo", "core", 4200),
new Employee("cy", "design", 2800),
new Employee("dia", "design", 3100));
List<String> names = staff.stream().map(Employee::name).collect(Collectors.toList());
Set<String> teams = staff.stream().map(Employee::team).collect(Collectors.toSet());
Map<String, Double> byName = staff.stream()
.collect(Collectors.toMap(Employee::name, Employee::salary));
Map<String, List<String>> grouped = staff.stream()
.collect(Collectors.groupingBy(Employee::team, Collectors.mapping(Employee::name, Collectors.toList())));
System.out.println("names : " + names);
System.out.println("teams : " + teams);
System.out.println("by name : " + byName);
System.out.println("grouped : " + grouped);
}
}The output is this.
names : [ana, bo, cy, dia]
teams : [core, design]
by name : {ana=3000.0, cy=2800.0, bo=4200.0, dia=3100.0}
grouped : {core=[ana, bo], design=[cy, dia]}Note the shape of the result. The toMap gave you a flat map from the name to the salary, and the groupingBy gave you a map from the team to a list of the names. That is a map of the lists, and it is the most common grouped shape that you will produce. The call Collectors.mapping inside the groupingBy is what transforms the elements before they are grouped. Without it, you would get a map of the lists of the whole objects.
What is the difference between groupingBy and partitioningBy?
The method groupingBy buckets by a key function and it can produce any number of the buckets. The method partitioningBy splits into exactly two, true and false, and it always returns both of the groups, even when one of them is empty. When the split is a yes-or-no question, then the partitioning is the better fit because it cannot lose a group.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class GroupingAndPartitioning {
record Task(String name, boolean done, int points) { }
public static void main(String[] args) {
List<Task> tasks = List.of(
new Task("write", true, 5),
new Task("review", true, 3),
new Task("deploy", false, 8),
new Task("refactor", false, 2));
Map<Boolean, List<Task>> byDone = tasks.stream()
.collect(Collectors.partitioningBy(Task::done));
System.out.println("done : " + byDone.get(true).size());
System.out.println("not done : " + byDone.get(false).size());
Map<Integer, List<String>> byPoints = tasks.stream()
.collect(Collectors.groupingBy(Task::points, Collectors.mapping(Task::name, Collectors.toList())));
System.out.println("by points : " + byPoints);
Map<Boolean, Long> counts = tasks.stream()
.collect(Collectors.partitioningBy(Task::done, Collectors.counting()));
System.out.println("counts : " + counts);
}
}The output is this.
done : 2
not done : 2
by points : {2=[refactor], 3=[review], 5=[write], 8=[deploy]}
counts : {false=2, true=2}Look at the map keys in the output. They are true and false, and not the string "true" that a groupingBy with a boolean key would produce. That difference matters when you later look up a group by the key. The third line shows the two-argument form of the partitioningBy, where a downstream counting() gives you the size of each side instead of the objects themselves.
Which other collectors are worth knowing?
counting()counts elements in a downstream collector.joining(delimiter)concatenates the elements into one string, with the optional prefix and suffix.summingIntand its friends sum a numeric field directly.toMapwith a merge function accumulates the duplicate keys instead of failing.filteringapplies a predicate to the elements inside a downstream collector.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class CollectorsCounting {
public static void main(String[] args) {
List<String> words = List.of("apple", "avocado", "banana", "blueberry", "cherry");
Map<Integer, Long> byLength = words.stream()
.collect(Collectors.groupingBy(String::length, Collectors.counting()));
System.out.println("by length : " + byLength);
long totalChars = words.stream().mapToLong(String::length).sum();
System.out.println("total characters : " + totalChars);
String joined = words.stream().collect(Collectors.joining(", "));
System.out.println("joined : " + joined);
String summary = words.stream().collect(Collectors.joining(", ", "[", "]"));
System.out.println("summary : " + summary);
}
}The output is this.
by length : {5=1, 6=2, 7=1, 9=1}
total characters : 33
joined : apple, avocado, banana, blueberry, cherry
summary : [apple, avocado, banana, blueberry, cherry]The joining is the collector to reach for when you need a single readable string out of a stream. It is a list of the names for an email, or a list of the tags for a summary. The two-argument form adds the prefix and the suffix, which saves you from concatenating the brackets around the result by hand.
What happens when two elements share a key?
The two-argument toMap throws an IllegalStateException because it cannot decide which value should win. The three-argument form takes a merge function and it tells it what to do. The fourth argument chooses the map implementation, which is how you get an insertion-ordered map.
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ToMapMerge {
record Sale(String region, int amount) { }
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("north", 10),
new Sale("south", 20),
new Sale("north", 15),
new Sale("east", 5));
Map<String, Integer> totals = sales.stream()
.collect(Collectors.toMap(Sale::region, Sale::amount, Integer::sum));
System.out.println("totals : " + totals);
try {
Map<String, Integer> broken = sales.stream()
.collect(Collectors.toMap(Sale::region, Sale::amount));
System.out.println(broken);
} catch (IllegalStateException e) {
System.out.println("duplicate key rejected : " + e.getClass().getSimpleName());
}
Map<String, Integer> linked = sales.stream()
.collect(Collectors.toMap(Sale::region, Sale::amount, Integer::sum, LinkedHashMap::new));
System.out.println("insertion ordered : " + linked.keySet());
}
}The output is this.
totals : {east=5, south=20, north=25}
duplicate key rejected : IllegalStateException
insertion ordered : [north, south, east]The exception in the middle of that output is the important part. The naive version of "sum sales per region" crashes as soon as a region appears twice, and the fix is one extra argument. The last line shows the fourth parameter producing a LinkedHashMap, so the keys come out in the order that they were first seen instead of an arbitrary hash order.
Which collector should you use?
| Goal | Collector |
|---|---|
| A plain list | toList() on the stream, or Collectors.toList() |
| Unique values | Collectors.toSet() |
| A lookup by key | Collectors.toMap |
| Groups by a field | Collectors.groupingBy |
| Yes or no split | Collectors.partitioningBy |
| A count per group | groupingBy with counting() |
| One text blob | Collectors.joining |
| Sum of a field | Collectors.summingInt or summingDouble |
Which downstream collectors are worth learning?
A downstream collector is the second argument that you pass to a grouping collector, and it decides what each group contains. The most useful ones mirror the terminal operations that you already know.
| Downstream | Each group holds | Typical use |
|---|---|---|
Collectors.toList() | A list of the elements | The default shape of a group |
Collectors.counting() | A number | How many in each group |
Collectors.mapping(...) | Transformed elements | Names inside a group by id |
Collectors.filtering(...) | Only the elements that pass | Counting a subset per group |
Collectors.summingInt(...) | A total | Spend per category |
Collectors.joining(", ") | One joined string | A readable summary per group |
The most useful pattern is a group with a total inside it, because it is two collectors combined.
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class DownstreamDemo {
record Sale(String region, int amount) { }
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("north", 10), new Sale("north", 15), new Sale("south", 20));
Map<String, Integer> totals = sales.stream()
.collect(Collectors.groupingBy(Sale::region, LinkedHashMap::new,
Collectors.summingInt(Sale::amount)));
Map<String, Long> counts = sales.stream()
.collect(Collectors.groupingBy(Sale::region, LinkedHashMap::new,
Collectors.counting()));
System.out.println("totals : " + totals);
System.out.println("counts : " + counts);
}
}The output is this.
totals : {north=25, south=20}
counts : {north=2, south=1}Two passes over the same data give you two different summaries, each one shaped by the downstream collector. That is the point of the design. The grouping decides the buckets, and the downstream decides what is in them.
The habits to keep
- Use
toList()for lists and collect for everything else. - Always think about the duplicate keys when you use
toMap. - Use
partitioningByfor a two-way split, andgroupingByfor many groups. - Combine a grouping with a downstream collector to get a summary instead of a pile of the objects.
- Pass
LinkedHashMap::newtotoMapwhen the order of the keys matters.
Try it yourself: take a list of the orders with a customer, a region and an amount. Collect them into a map from the customer to their total spend, then into a map from the region to a list of the order ids, and then into a map from the region to the number of the orders. Finally, join all of the customer names into a single comma-separated string and print it.