Collectors
collect is the terminal operation that builds a collection, and Collectors is the class of recipes for it: a list, a set, a joined text, a count, a map of groups. A group is itself a collection, so a collector may take another collector, which is the step that turns nine lines of loop into one.
toList, toSet and joining
The four recipes below take the same four words, one of which is repeated:
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Basics {
public static void main(String[] args) {
List<String> words = List.of("pear", "fig", "apple", "fig");
System.out.println(words.stream().collect(Collectors.toList()));
Set<String> unique = words.stream().collect(Collectors.toSet());
System.out.println(unique.size());
System.out.println(words.stream().collect(Collectors.joining(", ")));
System.out.println(words.stream().collect(Collectors.joining(", ", "[", "]")));
System.out.println(words.stream().distinct().collect(Collectors.joining("|")));
System.out.println(words.stream().collect(Collectors.counting()));
}
}
javac -Xlint:all Basics.java
java Basics
[pear, fig, apple, fig]
3
pear, fig, apple, fig
[pear, fig, apple, fig]
pear|fig|apple
4
The set drops the second fig, and the count of four is the count of the stream, not of the set. joining has three forms: a delimiter, then a delimiter with a prefix and a suffix, and the no-argument form for no separator at all. A pipeline of strings is the only thing joining accepts, so a number has to be mapped to text first.
groupingBy
groupingBy takes a classifier and answers a map from the key to the list of elements with that key. The three-argument form also takes a map supplier, which is how the groups come out in the order of a TreeMap:
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class Groups {
public static void main(String[] args) {
List<Person> people = List.of(
new Person("Ada", 36, "London"),
new Person("Alan", 41, "London"),
new Person("Grace", 45, "New York"),
new Person("Edsger", 36, "Amsterdam"));
Map<String, List<Person>> byCity = people.stream()
.collect(Collectors.groupingBy(Person::city, TreeMap::new, Collectors.toList()));
byCity.forEach((city, list) -> System.out.println(city + " " + list.size()));
Map<String, Long> countByCity = people.stream()
.collect(Collectors.groupingBy(Person::city, TreeMap::new, Collectors.counting()));
System.out.println(countByCity);
Map<String, List<String>> namesByCity = people.stream()
.collect(Collectors.groupingBy(Person::city, TreeMap::new,
Collectors.mapping(Person::name, Collectors.toList())));
System.out.println(namesByCity);
Map<Integer, List<String>> byAge = people.stream()
.collect(Collectors.groupingBy(Person::age, TreeMap::new,
Collectors.mapping(Person::name, Collectors.toList())));
System.out.println(byAge);
}
}
record Person(String name, int age, String city) {
}
javac -Xlint:all Groups.java
java Groups
Amsterdam 1
London 2
New York 1
{Amsterdam=1, London=2, New York=1}
{Amsterdam=[Edsger], London=[Ada, Alan], New York=[Grace]}
{36=[Ada, Edsger], 41=[Alan], 45=[Grace]}
The first map holds objects, the second holds counts and the third holds names, and all three come from the same list with one call each. The groups are in alphabetical order because the map is a TreeMap; with the one-argument form the order would be a HashMap order and the printout would be a guess.
A downstream collector
The last argument of groupingBy is a collector that runs inside each group. toList keeps the elements, counting counts them, mapping turns each of them into something else and then hands it to another collector, and joining makes text. The three-argument form of the lesson above uses two of them.
mapping(Person::name, toList()) reads as: for the elements of the group, apply the function, and collect the results into a list. A third level is possible, and the nesting is where a pipeline stops being clearer than a loop; two levels cover almost every report.
partitioningBy
partitioningBy is a grouping by a boolean, and its map always has both keys, even when one side is empty:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Partition {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6);
Map<Boolean, List<Integer>> odd = numbers.stream()
.collect(Collectors.partitioningBy(n -> n % 2 == 0));
System.out.println(odd.get(true));
System.out.println(odd.get(false));
Map<Boolean, Long> sizes = numbers.stream()
.collect(Collectors.partitioningBy(n -> n > 10, Collectors.counting()));
System.out.println(sizes);
}
}
javac -Xlint:all Partition.java
java Partition
[2, 4, 6]
[1, 3, 5]
{false=6, true=0}
The first partition keeps the evens and the odds, and the second one asks a question no element satisfies: the false side has all six and the true side has none, and both keys are there. A groupingBy with the same predicate would produce a map with one key, and the code that reads it would have to handle the absence.
toMap and the duplicate key
toMap takes a key function and a value function, and it refuses two elements with the same key unless a merge function says what to do. The program builds a map of word to length, one of length to word with the merge that joins the duplicates, and one without a merge that fails:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ToMap {
public static void main(String[] args) {
List<String> words = List.of("pear", "fig", "apple", "kiwi");
Map<String, Integer> byLength = words.stream()
.collect(Collectors.toMap(w -> w, String::length, (a, b) -> a));
System.out.println(byLength);
Map<Integer, String> longest = words.stream()
.collect(Collectors.toMap(String::length, w -> w, (a, b) -> a + "/" + b));
System.out.println(longest);
try {
words.stream().collect(Collectors.toMap(String::length, w -> w));
} catch (IllegalStateException e) {
System.out.println("duplicate key: " + e.getClass().getSimpleName());
}
}
}
javac -Xlint:all ToMap.java
java ToMap
{apple=5, kiwi=4, pear=4, fig=3}
{3=fig, 4=pear/kiwi, 5=apple}
duplicate key: IllegalStateException
pear and kiwi share the length 4, so the merge function runs for the second one and appends it to the first. Without a merge function the collector does not guess: it throws, and the message names the two values that collided, which the page does not print because the catch shows only the class. A toMap whose keys are not unique is a toMap that needs the third argument.
Exercises
- Join the names of Groups with a comma and a space, sorted.
- Count the people per age with groupingBy and counting.
- Partition the words of Basics by whether they contain the letter a and print both sides.
- Build a map of the first letter to the list of words with groupingBy and a downstream toList.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
Collectors.groupingByanswer?Answer
A map from the classifier key to the elements with that key
The classifier decides the key, and the default downstream collector is a list.
-
What does
joiningaccept as its elements?Answer
Strings, so a number has to be mapped to text first
The collector is typed on CharSequence, so the stream must be of strings.
-
Why does
partitioningByalways have both keys?Answer
The two sides are true and false, and an empty side is still a side
The partition of a set by a predicate always has both parts, one possibly empty.
-
What does this program print?
import java.util.List; import java.util.stream.Collectors; public class Q1 { public static void main(String[] args) { List<String> words = List.of("a", "bb", "c"); System.out.println(words.stream().collect(Collectors.joining("-"))); } }Answer
a-bb-c
The joining collector puts the delimiter between the elements.
-
What does this program print?
import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Q2 { public static void main(String[] args) { List<String> words = List.of("a", "b", "a"); Map<String, Long> counts = words.stream() .collect(Collectors.groupingBy(w -> w, Collectors.counting())); System.out.println(counts.get("a")); System.out.println(counts.size()); } }Answer
2 / 2
The word a appears twice and there are two distinct words.
-
What does this program print?
import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Q3 { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4); Map<Boolean, Long> parts = numbers.stream() .collect(Collectors.partitioningBy(n -> n > 2, Collectors.counting())); System.out.println(parts.get(true) + " " + parts.get(false)); } }Answer
2 2
Two numbers are greater than two and two are not.
-
What does this program print?
import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Q4 { public static void main(String[] args) { List<String> words = List.of("a", "bb"); Map<Integer, String> map = words.stream() .collect(Collectors.toMap(String::length, w -> w)); System.out.println(map.get(1) + map.get(2)); } }Answer
abb
The two lengths are different keys, so both entries are stored.
-
What does this program print?
import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Q5 { public static void main(String[] args) { List<String> words = List.of("a", "b"); Map<Integer, String> map = words.stream() .collect(Collectors.toMap(String::length, w -> w, (x, y) -> x + y)); System.out.println(map); } }Answer
{1=ab}
Both words have length one, so the merge function joins their values.
-
What happens when
toMapmeets a duplicate key and no merge function is given?Answer
The collector throws IllegalStateException
The collector refuses to guess which value the key should keep.
-
How is a group of objects turned into a group of names?
Answer
With Collectors.mapping as the downstream collector
mapping applies a function to each element of the group and collects the results.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev