首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Stream从对象列表中查找最常见的属性值

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

Stack Overflow用户
提问于 2017-04-26 00:39:12
回答 5查看 4.8K关注 0票数 21

我有两个类,它们的结构如下:

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对象列表,每个Person对象都可以获得一个标记值。

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

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

回答 5

Stack Overflow用户

发布于 2017-04-26 00:58:24

这对你来说应该是可行的:

private void run() {
    List<Person> list = Arrays.asList(() -> "foo", () -> "foo", () -> "foo",
                                      () -> "bar", () -> "bar");
    Map<String, Long> commonness = list.stream()
            .collect(Collectors.groupingBy(Person::getTag, Collectors.counting()));
    Optional<String> mostCommon = commonness.entrySet().stream()
            .max(Map.Entry.comparingByValue())
            .map(Map.Entry::getKey);
    System.out.println(mostCommon.orElse("no elements in list"));
}

public interface Person {
    String getTag();
}

commonness映射包含找到哪个标签的频率的信息。变量mostCommon包含最常找到的标记。此外,如果原始列表为空,则mostCommon为空。

票数 5
EN

Stack Overflow用户

发布于 2017-04-26 01:01:30

您可以将计数收集到地图中,然后获取具有最高值的密钥

List<String> foo = Arrays.asList("a","b","c","d","e","e","e","f","f","f","g");
Map<String, Long> f = foo
    .stream()
    .collect(Collectors.groupingBy(v -> v, Collectors.counting()));
String maxOccurence = 
            Collections.max(f.entrySet(), Comparator.comparing(Map.Entry::getValue)).getKey();

System.out.println(maxOccurence);
票数 5
EN

Stack Overflow用户

发布于 2017-04-26 12:46:49

如果您愿意使用第三方库,那么可以使用Eclipse Collections中的Collectors2和Java8 Stream来创建一个Bag并请求topOccurrences,这将返回一个MutableList of ObjectIntPair,它是标记值和出现次数的计数。

MutableList<ObjectIntPair<String>> topOccurrences = company.getPerson()
        .stream()
        .map(Person::getTag)
        .collect(Collectors2.toBag())
        .topOccurrences(1);
String mostCommonTag = topOccurrences.getFirst().getOne();

在平局的情况下,MutableList将有多个结果。

注意:我是Eclipse Collections的提交者。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43616422

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档