亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java 8 | 查找具有最大值大小的地圖條目

Java 8 | 查找具有最大值大小的地圖條目

繁星點點滴滴 2022-06-30 11:15:52
我有模型人 [城市,名稱]。我已在地圖中收集它們并按城市對它們進行分組。我需要追蹤最沒有人住在那里的城市,并只返回該條目作為地圖的一部分。我試過了,它也可以工作,但我想知道有沒有更好的方法。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 中編寫得更好。
查看完整描述

2 回答

?
阿波羅的戰車

TA貢獻1862條經驗 獲得超6個贊

獲得最大地圖條目后,您必須將其轉換為具有單個條目的地圖。為此,您可以使用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())單個條目來構建地圖。


查看完整回答
反對 回復 2022-06-30
?
holdtom

TA貢獻1805條經驗 獲得超10個贊

假設如果你有一個人員列表


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


查看完整回答
反對 回復 2022-06-30
  • 2 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號