【发布时间】: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