toMap, joining, and summarizing
Convert streams to maps, concatenate strings with joining, and compute stats with summarizingInt.
Collectors.toMap Basics
Collectors.toMap(keyMapper, valueMapper) converts a stream to a Map. Each element provides one key-value pair.
import java.util.*;
import java.util.stream.*;
record Country(String code, String name) {}
List<Country> countries = List.of(
new Country("US","United States"),
new Country("DE","Germany"),
new Country("JP","Japan")
);
Map<String, String> codeToName =
countries.stream().collect(
Collectors.toMap(Country::code, Country::name)
);
System.out.println(codeToName.get("DE")); // GermanyHandling Duplicate Keys
toMap throws IllegalStateException on duplicate keys. Supply a merge function as the third argument to resolve conflicts:
List<String> words = List.of("apple","ant","banana","bat","cherry");
Map<Character, String> firstByLetter =
words.stream().collect(
Collectors.toMap(
w -> w.charAt(0),
w -> w,
(existing, replacement) -> existing // keep first
)
);
System.out.println(firstByLetter); // {a=apple, b=banana, c=cherry}All lessons in this course
- groupingBy: Classifying Elements
- partitioningBy and counting
- toMap, joining, and summarizing
- Building a Custom Collector