gpt4 book ai didi

java - 使用 Stream 从对象列表中查找最常见的属性值

转载 作者:IT老高 更新时间:2023-10-28 20:57:03 25 4
gpt4 key购买 nike

我有两个类的结构如下:

public class Company {
private List<Person> person;
...
public List<Person> getPerson() {
return person;
}
...
}

public class Person {
private String tag;
...
public String getTag() {
return tag;
}
...
}

基本上Company类有一个Person对象的List,每个Person对象都可以得到一个Tag值。

如果我得到 Person 对象的列表,有没有办法使用 Java 8 中的 Stream 来找到所有 Person 对象中最常见的一个 Tag 值(如果是平局,可能只是随机最常见的)?

String mostCommonTag;
if(!company.getPerson().isEmpty) {
mostCommonTag = company.getPerson().stream() //How to do this in Stream?
}

最佳答案

String mostCommonTag = getPerson().stream()
// filter some person without a tag out
.filter(it -> Objects.nonNull(it.getTag()))
// summarize tags
.collect(Collectors.groupingBy(Person::getTag, Collectors.counting()))
// fetch the max entry
.entrySet().stream().max(Map.Entry.comparingByValue())
// map to tag
.map(Map.Entry::getKey).orElse(null);

ANDgetTag方法出现了两次,可以进一步简化代码:

String mostCommonTag = getPerson().stream()
// map person to tag & filter null tag out
.map(Person::getTag).filter(Objects::nonNull)
// summarize tags
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
// fetch the max entry
.entrySet().stream().max(Map.Entry.comparingByValue())
// map to tag
.map(Map.Entry::getKey).orElse(null);

关于java - 使用 Stream 从对象列表中查找最常见的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43616422/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com