【问题标题】:How do I get max country for a given arraylist如何获得给定数组列表的最大国家/地区
【发布时间】:2019-04-27 03:03:24
【问题描述】:

如何将结果集设置为 {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}

【问题讨论】:

    标签: java collections java-8 java-stream comparator


    【解决方案1】:

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

    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 之间。

    【讨论】:

    • Map.Entry mostFrequentEntry = numberOfStudentsByCountry.entrySet() .stream() .max(Map.Entry.comparingByValue()) // 此处可扩展 .orElse(null); // 可以根据服务默认
    • 以上作品
    【解决方案2】:
    Map.Entry<Country, Long> maxEntry = students.stream()
              .collect(groupingBy(Student::getCountry, counting()))
              .entrySet().stream().max(Map.Entry.comparingByValue()).get();
    

    【讨论】:

    • 您能否解释一下这段代码的作用?
    猜你喜欢
    • 2012-12-15
    • 2021-04-18
    • 2019-09-28
    • 2022-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多