Sub topic 7
Collecting into Lists, Sets, Maps, and Strings
A stream pipeline does its work and then has to hand you a result. Very often you want that result back in a normal Java container, such as a list you can pass to another method or a map you can look things up in. This chapter shows how to do that with the collect terminal operation and the ready-made helpers in the Collectors class.
What collect and a collector are
collect is a terminal operation. A terminal operation is the last step of a pipeline. It starts the work and produces the final result.
A collector is a recipe that tells collect how to gather elements. It answers three questions:
- What empty container should I start with?
- How do I add one element to it?
- What should I hand back at the end?
You rarely write a collector yourself. The class java.util.stream.Collectors gives you ready-made ones. You pass one of them to collect, like this: stream.collect(Collectors.toList()).
Collecting into a List
Collectors.toList() puts every element into a list. It keeps the order of the stream and keeps duplicates.
import java.util.List;
import java.util.stream.Collectors;
public class ToListExample {
public static void main(String[] args) {
List<String> colors = List.of("red", "blue", "red", "green");
List<String> upper = colors.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upper); // [RED, BLUE, RED, GREEN]
}
}The String::toUpperCase part is a method reference. It is a short way to write the lambda c -> c.toUpperCase().
Collecting into a Set
A set is a collection that holds each value only once. Collectors.toSet() drops duplicates for you.
There is one catch. The set it returns is usually a HashSet, and a HashSet does not keep elements in any particular order. If you print it, the order may look random. If you want a sorted set, ask for a TreeSet with Collectors.toCollection. A TreeSet keeps its elements sorted.
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class ToSetExample {
public static void main(String[] args) {
List<String> colors = List.of("red", "blue", "red", "green", "blue");
Set<String> unique = colors.stream()
.collect(Collectors.toSet());
System.out.println(unique.size()); // 3
TreeSet<String> sorted = colors.stream()
.collect(Collectors.toCollection(TreeSet::new));
System.out.println(sorted); // [blue, green, red]
}
}TreeSet::new is a constructor reference. It means "make a new, empty TreeSet." toCollection works with any collection type, such as ArrayList::new or LinkedList::new.
Collecting into a Map
A map stores pairs: each key points to one value. To build a map from a stream, you need to say two things for every element:
- What the key is. This is the key mapper.
- What the value is. This is the value mapper.
Collectors.toMap(keyMapper, valueMapper) takes both as functions.
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ToMapExample {
public static void main(String[] args) {
List<String> fruits = List.of("apple", "fig", "banana");
Map<String, Integer> lengths = fruits.stream()
.collect(Collectors.toMap(f -> f, String::length));
System.out.println(lengths.get("apple")); // 5
System.out.println(lengths.get("fig")); // 3
System.out.println(lengths.get("banana")); // 6
}
}Here each fruit is its own key, and its length is the value. The example prints with get because the result is usually a HashMap, which has no fixed order.
When two elements have the same key
A map can hold only one value per key. If two elements produce the same key, toMap does not know which value to keep, so it throws an IllegalStateException. You fix this by adding a third argument, a merge function. A merge function takes the old value and the new value and returns the one to keep.
You can also add a fourth argument to choose the map type. Passing TreeMap::new gives you a map sorted by key.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class ToMapMergeExample {
public static void main(String[] args) {
List<String> fruits = List.of("apple", "avocado", "banana", "blueberry", "cherry");
try {
fruits.stream()
.collect(Collectors.toMap(f -> f.charAt(0), f -> f));
} catch (IllegalStateException e) {
System.out.println("Duplicate key found");
}
Map<Character, String> byLetter = fruits.stream()
.collect(Collectors.toMap(
f -> f.charAt(0),
f -> f,
(oldValue, newValue) -> oldValue + "," + newValue,
TreeMap::new));
System.out.println(byLetter);
// {a=apple,avocado, b=banana,blueberry, c=cherry}
}
}If you want to group many elements under each key as a list, there is a better tool called groupingBy. A later chapter covers it.
Collecting into a String
Collectors.joining glues elements together into one String. It comes in three forms:
| Call | What it does | Result for a, b, c |
|---|---|---|
| `joining()` | Glues with nothing between | `abc` |
| `joining(", ")` | Puts a delimiter between elements | `a, b, c` |
| `joining(", ", "[", "]")` | Delimiter, plus a prefix and a suffix | `[a, b, c]` |
A delimiter is the text placed between items. A prefix goes at the very start, and a suffix goes at the very end.
joining only works on text, so each element must be a String or another CharSequence. To join numbers, turn them into strings first with map.
import java.util.List;
import java.util.stream.Collectors;
public class JoiningExample {
public static void main(String[] args) {
List<String> names = List.of("Ana", "Ben", "Cleo");
System.out.println(names.stream().collect(Collectors.joining()));
// AnaBenCleo
System.out.println(names.stream().collect(Collectors.joining(", ")));
// Ana, Ben, Cleo
System.out.println(names.stream().collect(Collectors.joining(" | ", "<", ">")));
// <Ana | Ben | Cleo>
List<Integer> scores = List.of(90, 75, 88);
String line = scores.stream()
.map(String::valueOf)
.collect(Collectors.joining("-"));
System.out.println(line); // 90-75-88
}
}If the stream is empty, joining(", ", "[", "]") still returns the prefix and suffix: [].
Choosing a collector
| You want | Use | Keeps order? | Keeps duplicates? |
|---|---|---|---|
| A list | `Collectors.toList()` | Yes | Yes |
| Unique values | `Collectors.toSet()` | No | No |
| A specific collection type | `Collectors.toCollection(TreeSet::new)` | Depends on type | Depends on type |
| Key-value lookup | `Collectors.toMap(k, v)` | No (unless you pass a map type) | Duplicate keys throw unless merged |
| One piece of text | `Collectors.joining(...)` | Yes | Yes |
Exercises
Exercise
Given List<String> words = List.of("cat", "dog", "cat", "eel"), write a pipeline that produces a TreeSet<String> of the unique words. What does it print?
Show answer
TreeSet<String> set = words.stream().collect(Collectors.toCollection(TreeSet::new)); System.out.println(set); prints [cat, dog, eel]. The duplicate "cat" is dropped, and the TreeSet keeps the words sorted.
Exercise
You run List.of("ant", "ape", "bee").stream().collect(Collectors.toMap(w -> w.length(), w -> w)). What happens, and how would you keep the longest... or rather the first word for each length?
Show answer
All three words have length 3, so toMap throws IllegalStateException because of a duplicate key. To keep the first word, add a merge function that returns the old value: Collectors.toMap(w -> w.length(), w -> w, (oldValue, newValue) -> oldValue). The result is {3=ant}.
Exercise
Given List<Integer> ids = List.of(4, 8, 15), write code that produces the String "IDs: 4/8/15".
Show answer
String s = ids.stream().map(String::valueOf).collect(Collectors.joining("/", "IDs: ", "")); The map step is needed because joining only accepts text elements.