Mastering Java Stream toMap: Handling Duplicate Keys with Ease
Learn how to effectively use Java's Stream API to convert a list of User objects into a Map, handle duplicate keys by providing a merge function, and avoid common pitfalls like IllegalStateException and NullPointerException using Optional and concise code examples.
Since Java 8, the Stream API has become indispensable for processing collections. Converting a list of User objects into a Map with Collectors.toMap is straightforward, but duplicate keys cause an IllegalStateException.
Define a simple User entity:
@Data
@AllArgsConstructor
public class User {
private int id;
private String name;
}Attempting to collect without handling duplicates:
public class UserTest {
@Test
public void demo() {
List<User> userList = new ArrayList<>();
// mock data
userList.add(new User(1, "Alex"));
userList.add(new User(1, "Beth"));
Map<Integer, String> map = userList.stream()
.collect(Collectors.toMap(User::getId, User::getName));
System.out.println(map);
}
}This throws IllegalStateException: duplicate key. The solution is to supply a third merge function to resolve conflicts:
Map<Integer, String> map = userList.stream()
.collect(Collectors.toMap(User::getId, User::getName, (oldData, newData) -> newData));When values may be null, combine Optional to provide a default:
Map<Integer, String> map = userList.stream()
.collect(Collectors.toMap(
User::getId,
it -> Optional.ofNullable(it.getName()).orElse(""),
(oldData, newData) -> newData));If you prefer an explicit loop, the same result can be achieved with a forEach on the list:
Map<Integer, String> map = new HashMap<>();
userList.forEach(it -> map.put(it.getId(), it.getName()));Using the Stream API together with Optional and a merge function provides a concise, readable way to build maps while safely handling duplicate keys and null values.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
