对集合根据id去重Java8中stream流的collectingAndThen用法

1.对集合根据id去重

//对集合的结果进行去重
        List<User> list = userList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getUserId))), ArrayList::new));
        System.out.println(list);

2.查找工资最高的员工的姓名:

//查找工资最高的员工的姓名
        String userName = userList.stream()
                .collect(Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparing(User::getSalary)),(Optional<User> user) -> user.map(User::getUserName).orElse(null)));
        System.out.println(userName);

3.计算用户工资的平均值:

//计算用户工资的平均值
        Double avgSalary = userList.stream()
                .collect(Collectors.collectingAndThen(Collectors.averagingDouble(User::getSalary), Double::doubleValue));
        System.out.println(avgSalary);

你可能感兴趣的:(Java开发,java,开发语言)