gpt4 book ai didi

Java 8 |查找具有最大值(value)大小的 map 条目

转载 作者:搜寻专家 更新时间:2023-11-01 01:15:28 30 4
gpt4 key购买 nike

我有模型 Person[city, name]。我在 map 中收集了它们,并按城市对它们进行了分组。我需要追踪最没有人住在那里的城市,并只返回该条目作为 map 的一部分。我已经尝试过并且它正在工作,但我想知道是否有更好的方法。

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 中编写得更好。

最佳答案

获取最大 map 条目后,您必须将其转换为具有单个条目的 map 。为此,您可以使用 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);

在 Java9 中,您可以使用 Map.of(e.getKey(), e.getValue()) 通过单个条目构建 map 。

关于Java 8 |查找具有最大值(value)大小的 map 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54799289/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com