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())單個條目來構建地圖。

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
添加回答
舉報