Medium java streams

Convert a list of employees to a map by id

The 30 second answer

I collect with toMap from id to the employee. The two-argument form throws if ids collide, so I pass a merge function when duplicates are possible. Null values also blow up because merge rejects them. If I need insertion order I use the four-argument form with LinkedHashMap.

Map<Long, Employee> byId = emps.stream()
    .collect(Collectors.toMap(Employee::id, Function.identity()));

Duplicate keys throw IllegalStateException in the two-arg form. Handle with a merge function: toMap(Employee::id, identity(), (a, b) -> a). Need encounter order → four-arg form with LinkedHashMap::new.

Null values throw NullPointerException (implementation uses Map.merge). [Impl] Java 10+: Collectors.toUnmodifiableMap.

Tip from the checklist: always discuss duplicate-key and null-value behavior for toMap.

Sources:

Sources (0)
See inline citations in the answer above.