// Created on savesnippets.com · https://savesnippets.com/98yC1Ht4SDGl1w import java.util.*; import java.util.stream.*; import static java.util.stream.Collectors.*; class Demo { record User(int id, String email) {} void example() { var users = List.of( new User(1, "alice@x.com"), new User(2, "bob@x.com"), new User(3, "alice@x.com") // duplicate email! ); // Index users by ID — unique, no collisions expected Map byId = users.stream() .collect(toMap(User::id, u -> u)); // Index by email — collision possible, must supply a merge function Map byEmail = users.stream() .collect(toMap( User::email, u -> u, (existing, replacement) -> existing // keep the first one )); System.out.println(byEmail); // Count occurrences by key Map emailCounts = users.stream() .collect(toMap(User::email, u -> 1L, Long::sum)); // {alice@x.com=2, bob@x.com=1} } }