Course contentsShow
← Java
Lesson 1519 of 2,87033. Streams API: Terminal OperationsFree lesson

Collectors.toMap() with Key and Value Mappers

Collecting elements into a Map by defining functions to extract keys and values from each stream element.

Collectors.toMap() with Key and Value Mappers

What You'll Learn

You'll learn how to collect stream elements into a Map by specifying custom functions that extract keys and values from each element.

The Core Idea

Up to now, you've collected streams into List and Set using toList() and toSet(). But what if you want a Map? Collectors.toMap() lets you transform each stream element into a key-value pair by providing two functions: one to extract the key, and another to extract the value.

Think of it like organizing a pile of business cards: you need to decide what becomes the index (the key—maybe the person's email) and what becomes the stored information (the value—maybe the person's full name).

Basic Syntax

Map<K, V> map = stream.collect(
    Collectors.toMap(keyMapper, valueMapper)
);
  • keyMapper: A Function that takes a stream element and returns its key
  • valueMapper: A Function that takes the same element and returns its value

Example: Building a Name-to-Age Map

List<String> names = List.of("Alice:25", "Bob:30", "Carol:28");

Map<String, Integer> nameToAge = names.stream()
    .collect(Collectors.toMap(
        s -> s.split(":")[0],  // key: extract name
        s -> Integer.parseInt(s.split(":")[1])  // value: extract age
    ));
// Result: {"Alice"=25, "Bob"=30, "Carol"=28}

Example: Identity as Key

List<String> words = List.of("apple", "banana", "cherry");

Map<String, Integer> wordLengths = words.stream()
    .collect(Collectors.toMap(
        word -> word,        // key: the word itself
        word -> word.length() // value: its length
    ));
// Result: {"apple"=5, "banana"=6, "cherry"=6}

Key Takeaway: Collectors.toMap(keyMapper, valueMapper) transforms each stream element into a Map entry by applying two functions—one for the key and one for the value—giving you complete control over how elements become key-value pairs.