从Java 8流中获取具有最大频率的对象 [英] Get object with max frequency from Java 8 stream
问题描述
我的对象有 city
和 zip
字段,我们称之为记录
。
I have an object with city
and zip
fields, let's call it Record
.
public class Record() {
private String zip;
private String city;
//getters and setters
}
现在,我有一个这些对象的集合,我使用以下代码按 zip
对它们进行分组:
Now, I have a collection of these objects, and I group them by zip
using the following code:
final Collection<Record> records; //populated collection of records
final Map<String, List<Record>> recordsByZip = records.stream()
.collect(Collectors.groupingBy(Record::getZip));
所以,现在我有一张地图,其中的键是 zip
,该值是记录
对象的列表,其中包含 zip
。
So, now I have a map where the key is the zip
and the value is a list of Record
objects with that zip
.
我现在想要获得的是每个 zip
最常见的 city
。
What I want to get now is the most common city
for each zip
.
recordsByZip.forEach((zip, records) -> {
final String mostCommonCity = //get most common city for these records
});
我想对所有流操作执行此操作。例如,我可以通过这样做获得每个 city
的频率图:
I would like to do this with all stream operations. For example, I am able to get a map of the frequency for each city
by doing this:
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
。
But I would like to be able to do a single-line stream operation that will just return the most frequent city
.
那里有没有Java 8流专家可以在这方面有所作为?
Are there any Java 8 stream gurus out there that can work some magic on this?
如果你想玩,这是 ideone沙盒用它来。
Here is an ideone sandbox if you'd like to play around with it.
推荐答案
您可以拥有以下内容:
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()
)
));
按邮政编码和城市分组每个记录,计算每个邮政编码的城市数量。然后,按邮政编码的城市数量地图进行后处理,以便仅保留最大数量的城市。
This groups each records by their zip, and by their cities, counting the number of cities for each zip. Then, the map of the number of cities by zip is post-processed to keep only the city having the maximum count.
这篇关于从Java 8流中获取具有最大频率的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!