Collectors.toMap throws on a duplicate key and NPEs on a null value

Both failures are runtime-only and neither is obvious from the call site. groupingBy tolerates duplicates; toMap does not. And toMap rejects null values even though HashMap accepts them.

Full code & output

This topic is available to PRO members.

Sign in Create a free account

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-25