san*_*dey 4 java java-8 java-stream
我有模特人[城市,名字].我已经在地图中收集它们并按城市分组.我需要追踪那些最没有人住在那里的城市,只返回该条目作为地图的一部分.我试过,它也在工作,但我想知道有没有更好的方法.
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));
Run Code Online (Sandbox Code Playgroud)
请建议我们如何在java 8中更好地编写.
假设你有一份人员名单
List<Person> persons = new ArrayList<Person>();
Run Code Online (Sandbox Code Playgroud)
然后,第一组由他们根据城市,然后即可通过列表最大值的条目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
Run Code Online (Sandbox Code Playgroud)
获取最大映射条目后,您必须将其转换为具有单个条目的映射.为此你可以使用Collections.singletonMap()
Map<String, List<Person>> mapOfMostPopulatedCity = persons.stream()
.collect(Collectors.groupingBy(Person::getCity)).entrySet().stream()
.max(Comparator.comparingInt(e -> e.getValue().size()))
.map(e -> Collections.singletonMap(e.getKey(), e.getValue()))
.orElseThrow(IllegalArgumentException::new);
Run Code Online (Sandbox Code Playgroud)
使用Java9,您可以使用Map.of(e.getKey(), e.getValue())单个条目构建地图.
| 归档时间: |
|
| 查看次数: |
115 次 |
| 最近记录: |