如何使用Java 8流获取每个不同键的第一个值? [英] How to get the first value for each distinct keys using Java 8 streams?
问题描述
例如:我有一个带有电子邮件的用户对象列表.我想收集具有不同电子邮件的用户列表(因为使用同一电子邮件的两个用户可能是同一个人,因此我不在乎这些差异).换句话说,对于每个不同的键(电子邮件),我想获取通过该键找到的第一个值(用户),而忽略其余的值.
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.
这是我想出的代码:
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?
推荐答案
您可以使用 values()
.
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());
}
这篇关于如何使用Java 8流获取每个不同键的第一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!