Java8stream流高级用法
简介
java8新添加了一个特性:流Stream。Stream让开发者能够以一种声明的方式处理数据源(集合、数组等),它专注于对数据源进行各种高效的聚合操作(aggregate operation)和大批量数据操作 (bulk data operation)。
用法
list根据某个属性去重
1 2 3 4
| businessProcesses = businessProcesses .stream() .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusinessProcess::getProcessId))), ArrayList::new));
|
list按某个属性正序排列
1 2 3
| businessProcesses = businessProcesses.stream().sorted(Comparator.comparing(BusinessProcess::getCreateTime)) .collect(Collectors.toList());
|
list按某个属性分组为map,key就是属性值,value是对应符合条件的list
1 2
| Map<String, List<BusinessProcess>> processGroupByDemandIdMap = childProcesses.stream().collect(Collectors.groupingBy(BusinessProcess::getDemandId));
|
根据关键字查询列表,关键字对应多个属性
1 2 3 4 5 6 7 8 9
| if (StringUtils.isNotEmpty(params.getSearchKeyWord())) { queryWrapper.and(wrapper -> wrapper.like(StringUtils.isNotBlank(params.getSearchKeyWord()), BtcUser::getUserCode, params.getSearchKeyWord()) .or() .like(StringUtils.isNotBlank(params.getSearchKeyWord()), BtcUser::getUserName, params.getSearchKeyWord()) .or() .like(StringUtils.isNotBlank(params.getSearchKeyWord()), BtcUser::getLoginAccount, params.getSearchKeyWord()) ); }
|
mybatisPlus根据lambda表达式设置updateWrapper
1 2 3 4 5 6
| LambdaUpdateWrapper<BtcDemandSnapshot> snapshotLambdaUpdateWrapper = new LambdaUpdateWrapper<BtcDemandSnapshot>() .set(BtcDemandSnapshot::getProjectCode, btcDemand.getProjectCode()) .eq(BtcDemandSnapshot::getDemandNumber, params.getDemandNumber()) .eq(BtcDemandSnapshot::getVersion, params.getVersion()); int demandSnapshotUpdateResult = btcDemandSnapshotMapper.update(null, snapshotLambdaUpdateWrapper);
|
对象list转map,key为对象中某个属性,value为对象本身
1
| Map<String, DemandInfoVo> demandMap = demandList.stream().collect(Collectors.toMap(DemandInfoVo::getDemandNumber, DemandInfoVo -> DemandInfoVo));
|
将对象集合按对象某个属性转成字符串并且用逗号分隔
1
| List<String> str = authorityList.stream().map(AuthorityQueryVo::getAuthorityName).collect(Collectors.joining(","));
|