美文网首页
java lambda常用表达式

java lambda常用表达式

作者: 漩涡丶路飞 | 来源:发表于2019-06-25 17:11 被阅读0次
    // 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());

    相关文章

      网友评论

          本文标题:java lambda常用表达式

          本文链接:https://www.haomeiwen.com/subject/vzktcctx.html