0Pricing
Java Academy · Lesson

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")); // Germany

Handling 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

  1. groupingBy: Classifying Elements
  2. partitioningBy and counting
  3. toMap, joining, and summarizing
  4. Building a Custom Collector
← Back to Java Academy