繁体   English   中英

从 Java 8 流中获取最大频率的对象

[英]Get object with max frequency from Java 8 stream

我有一个带有cityzip字段的对象,我们称之为Record

public class Record() {
    private String zip;
    private String city;

    //getters and setters
}

现在,我有这些对象的集合,并使用以下代码按zip对它们进行分组:

final Collection<Record> records; //populated collection of records
final Map<String, List<Record>> recordsByZip = records.stream()
    .collect(Collectors.groupingBy(Record::getZip));

所以,现在我有一个地图,其中键是zip ,值是带有该zipRecord对象列表。

我现在想得到的是每个zip最常见的city

recordsByZip.forEach((zip, records) -> {
    final String mostCommonCity = //get most common city for these records
});

我想用所有的流操作来做到这一点。 例如,通过执行以下操作,我可以获得每个city的频率图:

recordsByZip.forEach((zip, entries) -> {
    final Map<String, Long> frequencyMap = entries.stream()
        .map(GisSectorFileRecord::getCity)
        .filter(StringUtils::isNotBlank)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
});

但我希望能够进行单行流操作,该操作只会返回最频繁的city

是否有任何 Java 8 流专家可以在这方面发挥作用?

如果您想使用它,这里有一个ideone 沙箱

你可以有以下内容:

final Map<String, String> mostFrequentCities =
  records.stream()
         .collect(Collectors.groupingBy(
            Record::getZip,
            Collectors.collectingAndThen(
              Collectors.groupingBy(Record::getCity, Collectors.counting()),
              map -> map.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey()
            )
         ));

这将按每个记录的邮编和城市分组,计算每个邮编的城市数量。 然后,对 zip 的城市数量地图进行后处理以仅保留具有最大计数的城市。

我认为 Multiset 是此类问题的不错选择。 这是abacus-util的代码

Stream.of(records).map(e -> e.getCity()).filter(N::notNullOrEmpty)
      .toMultiset().maxOccurrences().get().getKey();

披露:我是AbacusUtil的开发者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM