Video in progress
What traps are there when you use Collectors.toMap?
If two keys turn out the same, an IllegalStateException: Duplicate key is thrown; if a value is null, you get an NPE. To avoid this, pass a merge function and, if needed, specify the map type explicitly.
📖 Answer
List<User> users = repo.findAll();
// if two users have the same email, this blows up on prod
Map<String, User> byEmail = users.stream()
.collect(Collectors.toMap(User::email, u -> u));
In tests everything is unique, so the bug stays hidden. On prod, old data that never checked email case shows up.
The safe version:
Map<String, User> byEmail = users.stream()
.collect(Collectors.toMap(
User::email,
Function.identity(),
(first, second) -> first, // what to do on a duplicate
LinkedHashMap::new)); // if you need ordering
About null values: toMap uses HashMap.merge internally, and that does not accept a null value. If u -> u.middleName() returns null, you get an NPE, even though HashMap itself allows null.
If you need several values per key, don't use toMap; use groupingBy: Collectors.groupingBy(User::city) → Map<String, List<User>>.
Sign up to mark studied questions and save your progress.