Sub topic 7
Collecting into Lists, Sets, Maps, and Strings
A stream does not hold your results. When the pipeline finishes, you usually want the data back in a form you can keep and use. The collect method does this.
collect is a terminal operation. A terminal operation is the last step of a pipeline: it runs the pipeline and produces a result. You pass collect a collector. A collector is a recipe that tells Java how to gather the elements into one container. The Collectors class, in the java.util.stream package, has ready-made collectors for the most common containers.
The four basic collectors
| Collector | Result | Good for |
|---|---|---|
| `Collectors.toList()` | `List` | Keeping every element in order |
| `Collectors.toSet()` | `Set` | Keeping one copy of each value |
| `Collectors.toMap(key, value)` | `Map` | Looking up a value by key |
| `Collectors.joining(", ")` | `String` | Building readable text |
A worked example
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class CollectExample {
public static void main(String[] args) {
List<String> fruits = List.of("apple", "banana", "apple", "cherry");
List<String> upper = fruits.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(upper); // [APPLE, BANANA, APPLE, CHERRY]
Set<String> unique = fruits.stream()
.collect(Collectors.toSet());
System.out.println(unique.size()); // 3
List<String> names = List.of("kiwi", "mango", "fig");
Map<String, Integer> lengths = names.stream()
.collect(Collectors.toMap(name -> name, String::length));
System.out.println(lengths.get("mango")); // 5
String joined = fruits.stream()
.collect(Collectors.joining(", ", "[", "]"));
System.out.println(joined); // [apple, banana, apple, cherry]
}
}Here is what each part does:
toList()keeps all four fruits, including both copies of "apple", in their original order.toSet()drops the duplicate "apple", so the set has 3 elements. ASetmakes no promise about order.toMaptakes two functions. The first one picks the key, and the second one picks the value. Here each name becomes a key, and its length becomes the value.joiningglues strings together. The first argument goes between elements. The optional second and third arguments are a prefix and a suffix.
Exercise
You have List.of(3, 1, 2). Write a pipeline that turns it into the String "3-1-2".
Show answer
List.of(3, 1, 2).stream().map(String::valueOf).collect(Collectors.joining("-")). The map step turns each Integer into a String, which joining requires.
Exercise
What happens if you run List.of("ant", "bee", "ant").stream().collect(Collectors.toMap(w -> w, String::length))? How would you fix it?
Show answer
It throws IllegalStateException because the key "ant" appears twice. Add a merge function as a third argument, for example Collectors.toMap(w -> w, String::length, (a, b) -> a), to keep one value for the repeated key.