java lambda常用表达式

// List转Map
Map<Long, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));

// 如果list中getId有重复,需添加重复key策略,否则转换的时候会报重复key的异常,如下,u1和u2的位置决定当出现重复key时使用前者还是后者
userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (u1, u2) -> u2));

// List转某个字段的List
List<Long> userIdList = userList.stream().map(User::getId).collect(Collectors.toList());

// List根据某个字段分组
Map<Long, List<User>> userListMap = userList.stream().collect(Collectors.groupingBy(User::getId));

// List根据对象中某个字段去重
List<User> distinctUserList = userList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getId))), ArrayList::new));

// 简单类型list去重
List<Integer> newUserIdList = userIdList.stream().distinct().collect(Collectors.toList());

// String类型List以逗号隔开转为字符串
String userNames = String.join(",", userNameList);

// Integer类型List以逗号隔开转为字符串
String userIds = userIdList.stream().map(String::valueOf).collect(Collectors.joining(","));

// List根据条件过滤元素
List<Long> userFilterIdList = userIdList.stream().filter(id -> !userListA.contains(id)).collect(Collectors.toList());

// List根据某个属性汇总
int sum = userList.stream().mapToInt(User::getAge).sum();
BigDecimal bigDecimalSum = userList.stream().map(User::getValue).reduce(BigDecimal.ZERO, BigDecimal::add);

// List根据某个属性排序,默认正序
userList.sort(Comparator.comparing(User::getAge));

// List根据某个属性排序,倒序
userList.sort(( User user1, User user2) -> user2.getAge() - user1.getAge());

// 并行执行
userList = userIdList.parallelStream().map(user -> userService.selectList(userList))
                .flatMap(Collection::stream).collect(Collectors.toList());

// 排序
userList = userList.stream()
        .sorted(Comparator.comparing(User::getAge).reversed()
            .thenComparing(
                (User o1, User o2) -> o2.getSort() - o1.getSort())
            .thenComparing(User::getName))
        .collect(Collectors.toList());
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。