首页 > 解决方案 > 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 中编写得更好。

标签: javajava-8java-stream

解决方案


假设如果你有一个人员列表

List<Person> persons = new ArrayList<Person>();

然后首先根据城市对他们进行分组,然后获取列表中具有最大值的条目max将返回OptionalEntry所以我不会让它变得复杂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

推荐阅读