从Java8流获取最大频率的对象
我有一个带有从Java8流获取最大频率的对象,java,java-8,java-stream,Java,Java 8,Java Stream,我有一个带有city和zip字段的对象,我们称它为Record public class Record() { private String zip; private String city; //getters and setters } 现在,我有了这些对象的集合,并使用以下代码按zip对它们进行分组: final Collection<Record> records; //populated collection of records final M
city
和zip
字段的对象,我们称它为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));
我希望对所有流操作都这样做。例如,我可以通过以下操作获得每个城市的频率图:
recordsByZip.forEach((zip, entries) -> {
final Map<String, Long> frequencyMap = entries.stream()
.map(GisSectorFileRecord::getCity)
.filter(StringUtils::isNotBlank)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
});
recordsByZip.forEach((zip,条目)->{
最终映射频率Map=entries.stream()
.map(GisSectorFileRecord::getCity)
.filter(StringUtils::isNotBlank)
.collect(Collectors.groupingBy(Function.identity()、Collectors.counting());
});
但我希望能够执行单行流操作,只返回最频繁的city
有没有Java8流大师可以在这方面发挥神奇的作用
如果你想玩它,这里有一个例子。你可以有以下几点:
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()
)
));
最热门城市最终地图=
records.stream()
.collect(收集器.groupingBy(
记录::getZip,
收藏,收藏,然后(
Collectors.groupingBy(Record::getCity,Collectors.counting()),
map->map.entrySet().stream().max(map.Entry.comparingByValue()).get().getKey()
)
));
这组数据按邮政编码和城市进行记录,计算每个邮政编码的城市数。然后,通过zip对城市数量的地图进行后处理,只保留数量最多的城市。我认为Multiset是解决此类问题的一个好选择。这是密码
披露:我是AbacusUtil的开发者。收集,然后
我知道我遗漏了一些东西,但我总是想到映射+1在调用.get()
之前,是否有方法检查流操作中是否存在由.max()
返回的可选
,它必须包含至少一个按zip分组的城市。你怎么能先调用它?在我的实际应用程序中,地图可能是空的,因为city
可以为空,我首先调用filter
来过滤city
为null
的记录。因此,如果一个zip
只有一条记录,而该记录的null
city
,那么该可选项就不存在了。@AndrewMairose我明白了,您可以调用.get().getKey()
,而不是.map(map.Entry::getKey.).orElse(null)
,如果地图为空,对于最常见的城市,它将返回null
。请添加代码片段(最好)或链接到代码片段(至少)
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()
)
));
Stream.of(records).map(e -> e.getCity()).filter(N::notNullOrEmpty)
.toMultiset().maxOccurrences().get().getKey();