Javaの8 | 値の最高サイズで検索マップエントリ

サンディープ・パンディー:

私は、モデル人[都市、名]を持っています。私は地図にそれらを収集し、市内でそれらをグループ化しています。私はほとんどありませんそこに滞在する人の持って街をトレースし、地図の一部として、そのエントリだけを返す必要があります。I'vはやって、任意のより良い方法があり、それが働いているが、私は思っていたにも試してみました。

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でより良い書き込むことができますどのように提案してください。

ラビンドラRanwala:

最大マップエントリを取得した後、あなたは、単一のエントリを持っているマップにそれを変換する必要があります。あなたが使用できるため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())、単一のエントリでマップを構築します。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=183164&siteId=1