CKTIS / Java
Collectors.toMap: practical reference
Collectors.toMap: practical reference: Collectors.toMap creates a Map from key and value mapping functions; overloads control duplicate-key merging and the concrete map supplier.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
Collectors.toMap(...)Collectors.toMap creates a Map from key and value mapping functions; overloads control duplicate-key merging and the concrete map supplier.
Use it to build an index when each element has a stable key and duplicate policy is explicit.
The two-function overload throws IllegalStateException on duplicate keys. Null handling depends on Map.merge and the chosen implementation, so null keys or values should not be assumed safe.
Empty input yields an empty map. A merge function that returns null removes the mapping according to Map.merge semantics.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var map = java.util.stream.Stream.of("a", "bb", "c")
.collect(java.util.stream.Collectors.toMap(String::length, s -> s, (left, right) -> left + right, java.util.TreeMap::new));
System.out.println(map);
}
}
Result
{1=ac, 2=bb}The example exercises the documented element in a small deterministic program and compares exact standard output.