Java8Lamda表达式使用整理持续更新

    技术2022-07-11  93

    Java8Lamda表达式使用 整理持续更新

    // StringList 转 IntegerList List<Integer> integerList = stringList.parallelStream() .map(Integer :: parseInt).collect(Collectors.toList()));

    业务场景:导入部门数据(Excel中提供了部门对应的orgCode,orgCode用于作为部门的树权限查询:例如浙江省的orgCode为3000,杭州市为3000.0001,上城区为3000.0001.0001来进行部门权限管理): 若感兴趣可以看一下完整的代码结构

    //根据部门的orgCode长度进行分组,排序(排序是为了保证区域的id在前面按照顺序导入,这样之后的查询结果也是按照顺序查询出来的与Excel中的内容保持一致) TreeMap<Integer, List<OrgDeptPo>> orgMap = areaList.parallelStream() .collect(Collectors.groupingBy(OrgDeptPo :: gainOrgCodeLength, TreeMap :: new , Collectors.collectingAndThen( Collectors.toCollection(() -> new TreeSet<> (Comparator.comparing(OrgDeptPo::getSortIndex))), ArrayList::new)));

    //根据某一字段去重(默认保留靠前对象,若要保留新的,需要先做一次.reverse):

    list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection( // 利用 TreeSet 的排序去重构造函数来达到去重元素的目的 // 根据firstName去重 () -> new TreeSet<>(Comparator.comparing(Pojo::getId))), ArrayList::new));

    //覆盖已有值(o1,o2) -> o2

    map = (HashMap<String, Integer>) list.parallelStream() .collect(Collectors.toMap(Pojo::getName, Pojo::getId,(o1,o2) -> o2)); //判断是否含有type为1的数据 boolean isExist = list.parallelStream().mapToInt(Pojo::getType) .anyMatch(x -> x == 1); //根据某字段进行分组后,在将id抽取出来作为map的value值。 Map<Integer, List<Integer>> groupMap = list.parallelStream() .collect(groupingBy(Pojo::getGroupId, Collectors.mapping(Pojo :: getId,Collectors.toList()))); //filter的使用,过滤掉不满足条件的数据(判断返回为false) List<Integer> as = new ArrayList<>(); as.add(1); as.add(2); as = as.parallelStream().filter(x -> x.equals(1)).collect(Collectors.toList()); //剩下1

    Optional的使用

    //判断是否查询结果为空,若不为空给param设值 Pojo param = new Pojo(); Optional.ofNullable(testDao.getParamByToken(token)).ifPresent(x -> param.setAccId(x.getId())); //orElse 为空时重新赋值 return Optional.ofNullable(testDao.getParamByToken(token)) .orElse(new Param().setParamName("没有对应数据"));

    JAVA8没有 ifPresent和orElse的联合使用JAVA9有ifPresenOrElse的用法

    Processed: 0.010, SQL: 9