How to get the first value for each distinct keys using Java 8 streams?

喜欢而已 提交于 2020-07-29 06:37:57

问题


For example: I have a list of user objects with e-mails. I would like to collect the list of users with distinct e-mails (because two users with the same e-mail would be probably the same person, so I do not care about the differences). In other words, for each distinct key (e-mail), I want to grab the first value (user) found with that key and ignore the rest.

This is a code I have came up with:

public List<User> getUsersToInvite(List<User> users) {
    return users
            .stream()
            // group users by their e-mail
            // the resulting map structure: email -> [user]
            .collect(Collectors.groupingBy(User::getEmail, LinkedHashMap::new, Collectors.toList()))
            // browse each map entry
            .entrySet()
            .stream()
            // get the first user object for each entry
            .map(entry -> entry.getValue().get(0))
            // collect such first entries into a list
            .collect(Collectors.toList());
}

Is there some more elegant way?


回答1:


You can use Collectors.toMap(keyMapper, valueMapper, mergeFunction), use the e-mail as key, user as value and ignore the key conflicts by always returning the first value. From the Map, you can then get the users by calling values().

public List<User> getUsersToInvite(List<User> users) {
    return new ArrayList<>(users.stream()
                                .collect(Collectors.toMap(User::getEmail, 
                                                          Function.identity(), 
                                                          (u1, u2) -> u1))
                                .values());
}


来源:https://stackoverflow.com/questions/33015853/how-to-get-the-first-value-for-each-distinct-keys-using-java-8-streams

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!