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
| @Test public void test() throws InterruptedException { List<User> list = new ArrayList<User>() {{ add(new User("半月1", 18, 90)); add(new User("半月2", 18, 80)); add(new User("半月3", 18, 70)); add(new User("半月4", 18, 60)); add(new User("半月无霜1", 20, 90)); add(new User("半月无霜2", 20, 80)); add(new User("半月无霜3", 20, 70)); add(new User("半月无霜4", 20, 60)); }}; Map<Integer, List<User>> groupByScore = list.stream().collect(Collectors.groupingBy( User::getScore, Collectors.mapping(Function.identity(), Collectors.toList()) )); Map<Integer, Optional<Integer>> maxScoreByAge = list.stream().collect(Collectors.groupingBy( User::getAge, Collectors.mapping(User::getScore, Collectors.maxBy(Integer::compareTo)) )); Map<Boolean, Optional<Integer>> maxScoreByPassMark = list.stream().collect(Collectors.partitioningBy( user -> user.getScore() >= 60, Collectors.mapping(User::getScore, Collectors.maxBy(Integer::compareTo)) ));
maxScoreByPassMark.keySet().forEach(a -> System.out.println("是否及格:" + a + ":" + maxScoreByPassMark.get(a))); }
@Data @AllArgsConstructor class User{ private String name; private Integer age; private Integer score; }
|