Java SE API

Collectors.toMap()

Builds a map with explicit collision handling and map supplier. Avoid null mapped values. Java SE API; example uses Java 21-compatible syntax.

Formal Syntax & Structure

java syntaxjava
static <T,K,U,M extends Map<K,U>> Collector<T,?,M> toMap(Function<? super T,? extends K> keyMapper, Function<? super T,? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapFactory)

Parameters & Attributes

NameTypeDescription
keyMapperFunction<? super T,? extends K>Key extraction
valueMapperFunction<? super T,? extends U>Value extraction
mergeFunctionBinaryOperator<U>Collision policy
mapFactorySupplier<M>New empty map

Return Value

Collector<T,?,M>

Builds a map with explicit collision handling and map supplier. Avoid null mapped values.

Working Example

Example Snippetjava
import java.util.*;import java.util.stream.*;public class Main {    public static void main(String[] args) {        record Line(String code, int units) {}        var lines = List.of(new Line("B", 2), new Line("A", 3), new Line("B", 5));        Map<String, Integer> totals = lines.stream().collect(Collectors.toMap(Line::code, Line::units, Integer::sum, TreeMap::new));        System.out.println(totals);    }}
Java Reference