どのように私は与えられたArrayListのための最大の国を得るのですか

sekhar:

どのように私が代わりに{ドイツ= 3、POLAND = 2、英国= 3}の{ドイツ= 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などの値で比較します:

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

あなたは1つだけに興味があるなら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あなたは、このような周波数は、両国のために等しいとしてタイを破るしたい場合、カスタム・ロジック。ただ、たとえば、言うために、これは間を発生することがドイツ英国のサンプルデータで。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=181886&siteId=1