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.

macrozheng
macrozheng
macrozheng
Mastering Java Stream toMap: Handling Duplicate Keys with Ease

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaoptionalStream APIDuplicate KeyCollectorstoMap
macrozheng
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.