java - Java 8 | 查找具有最大值大小的地图条目
问题描述
我有模型人 [城市,名称]。我已在地图中收集它们并按城市对它们进行分组。我需要追踪最没有人住在那里的城市,并只返回该条目作为地图的一部分。我试过了,它也可以工作,但我想知道有没有更好的方法。
Comparator<Entry<String, List<Person>>> compareByCityPopulation =
Comparator.comparing(Entry<String, List<Person>>::getValue, (s1, s2) -> {
return s1.size() - s2.size();
});
HashMap mapOfMostPopulatedCity = persons.stream()
.collect(Collectors.collectingAndThen(Collectors.groupingBy(Person::getCity), m -> {
Entry<String, List<Person>> found = m.entrySet().stream().max(compareByCityPopulation).get();
HashMap<String, List<Person>> hMap = new HashMap<>();
hMap.put(found.getKey(), found.getValue());
return hMap;
}));
System.out.println("*City with Most no of people*");
mapOfMostPopulatedCity.forEach((place, peopleDetail) -> System.out.println("Places " + place + "-people detail-" + peopleDetail));
请建议我们如何在 java 8 中编写得更好。
解决方案
假设如果你有一个人员列表
List<Person> persons = new ArrayList<Person>();
然后首先根据城市对他们进行分组,然后获取列表中具有最大值的条目max
将返回Optional
,Entry
所以我不会让它变得复杂HashMap
,如果结果出现在可选中,我将只使用它来存储结果,否则将返回空Map
Map<String, List<Person>> resultMap = new HashMap<>();
persons.stream()
.collect(Collectors.groupingBy(Person::getCity)) //group by city gives Map<String,List<Person>>
.entrySet()
.stream()
.max(Comparator.comparingInt(value->value.getValue().size())) // return the Optional<Entry<String, List<Person>>>
.ifPresent(entry->resultMap.put(entry.getKey(),entry.getValue()));
//finally return resultMap
推荐阅读
- c# - C# foreach 循环和匹配。有没有更快的方法来做到这一点?
- javascript - React - 如何按索引更改类名?
- python - 外乘两个大型一维数组的有效方法
- javascript - Workbox:当有一个新的服务工作者时,它会加载但等待
- python - TypeError:“图像”对象不可下标
- java - Android = select column1 from table where column2 = column3 order by id desc
- byte-buddy - 使用 isSubTypeOf 时排除特定子类型
- python - python应用程序调用kubernetes以编程方式创建pod
- javascript - 在 FullCalendar 回调中查找显示类型
- laravel - 目标 [Laravel\Fortify\Contracts\ResetsUserPasswords] 不可实例化