我目前正在尝试找到从集合中的所有项目中查找最常见名称的最佳方法。
Set 中的对象是 Person 对象:
public class Person {
private String name;
...
public String getName() {
return name;
}
}
在 findMostCommonName 方法中,我想查找给定集合中所有 Person 对象的最常见名称。 Java 8 有办法做到这一点吗?
public String findMostCommonName(Set<Person> personSet) {
//Code here
}
谢谢。
最佳答案
你可以使用
public String findMostCommonName(Set<Person> personSet) {
return personSet.stream().map(Person::getName)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue()).map(Map.Entry::getKey)
.orElse(null);
}
personSet.stream().map(Person::getName)
直接创建名称字符串流,.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
将出现的次数计入 Map<String,Long>
,然后.entrySet().stream()
将流过条目和 .max(Map.Entry.comparingByValue()).map(Map.Entry::getKey)
将找到具有最高值的条目,即计数,并提取 key ,即具有该计数的字符串。
最后.orElse(null)
决定没有结果时如何处理,即personSet
是空的。如果您使用get()
相反,NoSuchElementException
在这种情况下将被抛出。
如果出现平局,将返回出现次数最多的名称中的任意名称。
关于java - 使用 Java 8 获取 Set 中所有项目最常见名称的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43075589/