java lambda常用表达式

// List转Map
Map 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 userIdList = userList.stream().map(User::getId).collect(Collectors.toList());

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

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

// 简单类型list去重
List 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 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());

你可能感兴趣的:(java lambda常用表达式)