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

前端 未结 1 998
时光说笑
时光说笑 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 getUsersToInvite(List users) {
        return new ArrayList<>(users.stream()
                                    .collect(Collectors.toMap(User::getEmail, 
                                                              Function.identity(), 
                                                              (u1, u2) -> u1))
                                    .values());
    }
    

    0 讨论(0)
提交回复
热议问题