1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| public class MyTest { public static void main(String[] args) { List<Stu> list = new ArrayList<>(); list.add(new Stu("张三", 100,"101")); list.add(new Stu("李四", 110,"103")); list.add(new Stu("王五", 80,"101")); list.add(new Stu("赵六", 90,"105")); list.add(new Stu("孙七", 70,"105")); list.add(new Stu("钱八", 60,"106")); list.add(new Stu("李九", 50,"105")); list.add(new Stu("赵十", 40,"104")); list.add(new Stu("孙十一", 30,"105")); list.add(new Stu("钱十二", 20,"104")); list.add(new Stu("李十三", 10,"106")); list.add(new Stu("赵十四", 15,"106")); list.add(new Stu("孙十五", 65,"107")); list.add(new Stu("钱十六", 78,"103")); list.add(new Stu("李十七", 96,"107")); list.add(new Stu("赵十八", 30,"106")); list.add(new Stu("孙十九", 28,"102")); list.add(new Stu("钱二十", 102,"101")); list.add(new Stu("孙二十一", 98,"102")); list.add(new Stu("钱二十三", 66,"102"));
Map<String, Map<String, Integer>> collect = list.stream() .collect( Collectors.groupingBy( Stu::getRoom, Collectors.collectingAndThen( Collectors.toMap(Stu::getName, Stu::getScore), map->map.entrySet().stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) .limit(2) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) ) ) );
collect.entrySet().stream().forEach(System.out::println); } }
|