gpt4 book ai didi

java - 如何获得给定数组列表的最大国家/地区

转载 作者:搜寻专家 更新时间:2023-10-31 20:25:05 24 4
gpt4 key购买 nike

如何将结果集设置为 {GERMANY=3} 而不是 {GERMANY=3, POLAND=2, UK=3}

public class Student {
private final String name;
private final int age;
private final Country country;
private final int score;

// getters and setters (omitted for brevity)
}

public enum Country { POLAND, UK, GERMANY }


//Consider below code snippet

public static void main(String[] args) {
List<Student> students = Arrays.asList(
/* NAME AGE COUNTRY SCORE */
new Student("Jan", 13, Country.POLAND, 92),
new Student("Anna", 15, Country.POLAND, 95),
new Student("Helga", 14, Country.GERMANY, 93),
new Student("Leon", 14, Country.GERMANY, 97),
new Student("Chris", 15, Country.GERMANY, 97),
new Student("Michael", 14, Country.UK, 90),
new Student("Tim", 15, Country.UK, 91),
new Student("George", 14, Country.UK, 98)
);

// Java 8 code to get all countries code but
// How do I get the only country that has maximum students from ArrayList given above.

Map<Country, Long> numberOfStudentsByCountry =
students.stream()
.collect(groupingBy(Student::getCountry, counting()));
System.out.println(numberOfStudentsByCountry);
}

结果如下

 {GERMANY=3, POLAND=2, UK=3}

我想要像下面这样的。

 {GERMANY=3}

最佳答案

您可以使用 Stream.max 比较以下值进一步获取 map 中出现频率最高的国家/地区:

Country mostFrequent = numberOfStudentsByCountry.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(Country.POLAND) // some default country

如果您只对单个 Map.Entry 感兴趣,您可以使用

Map.Entry<Country,Long> mostFrequentEntry = numberOfStudentsByCountry.entrySet()
.stream()
.max(Map.Entry.comparingByValue()) // extensible here
.orElse(null); // you can default according to service

注意:这两个都应该具有足够的可扩展性,以便在您想要打破平局时向 Comparator 添加自定义逻辑,例如频率对两个国家来说是平等的。举例来说,这可能发生在示例数据中的 GERMANYUK 之间。

关于java - 如何获得给定数组列表的最大国家/地区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53464666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com