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<Integer, User> byId = users.stream()
.collect(toMap(User::id, u -> u));
// Index by email — collision possible, must supply a merge function
Map<String, User> 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<String, Long> emailCounts = users.stream()
.collect(toMap(User::email, u -> 1L, Long::sum));
// {alice@x.com=2, bob@x.com=1}
}
}
Create a free account and build your private vault. Share publicly whenever you want.