sek*_*har 5 java collections comparator java-8 java-stream
如何将结果集设为{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);
}
Run Code Online (Sandbox Code Playgroud)
结果如下
{GERMANY=3, POLAND=2, UK=3}
Run Code Online (Sandbox Code Playgroud)
我想在下面.
{GERMANY=3}
Run Code Online (Sandbox Code Playgroud)
Stream.max您可以通过比较值来进一步获取地图中最常见的国家/地区:
Country mostFrequent = numberOfStudentsByCountry.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(Country.POLAND) // some default country
Run Code Online (Sandbox Code Playgroud)
如果您只对单个感兴趣Map.Entry,您可以使用
Map.Entry<Country,Long> mostFrequentEntry = numberOfStudentsByCountry.entrySet()
.stream()
.max(Map.Entry.comparingByValue()) // extensible here
.orElse(null); // you can default according to service
Run Code Online (Sandbox Code Playgroud)
注意Comparator:当您想要打破平局(例如两个国家的频率相等)时,这两个都应该具有足够的可扩展性,以便添加到举例来说,在样本数据中,这种情况可能发生在德国和英国之间。
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |