打印大多数人所在的国家



我已经实现了这个逻辑来打印大多数人的国家。我有一个有年龄、国家和名字的Person类。

Map<String, Long> c = people.stream().collect((Collectors.groupingBy((Person::getCountry),(Collectors.counting()))));
Long f = Collections.max(c.values());
for (Map.Entry i : c.entrySet()) 
if (i.getValue()==f)
System.out.println(i.getKey() + " - " + i.getValue());

它能用更短的方式写吗?

var c = people.stream()
.collect((Collectors.groupingBy((Person::getCountry), (Collectors.counting()))))
.entrySet().stream()
.max((o1, o2) -> Long.compare(o2.getValue(), o1.getValue())).get().getKey();

组合两个答案:

var mostPopulousCountry = people.stream()
.collect(Collectors.groupingBy(Person::getCountry, Collectors.counting()))
.entrySet().stream()
.max(Map.Entry.comparingByValue())
.get().getKey(); 

最新更新