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

前端 未结 1 1005
时光说笑
时光说笑 2021-01-05 18:29

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 pro

相关标签:
1条回答
  • 2021-01-05 19:21

    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());
    }
    
    0 讨论(0)
提交回复
热议问题