Java8stream流高级用法

Java8stream流高级用法

简介

java8新添加了一个特性:流Stream。Stream让开发者能够以一种声明的方式处理数据源(集合、数组等),它专注于对数据源进行各种高效的聚合操作(aggregate operation)和大批量数据操作 (bulk data operation)。

用法

list根据某个属性去重
1
2
3
4
// 示例为根据processId属性去重 
businessProcesses = businessProcesses
.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(BusinessProcess::getProcessId))), ArrayList::new));
list按某个属性正序排列
1
2
3
// 示例为根据createTime属性排序
businessProcesses = businessProcesses.stream().sorted(Comparator.comparing(BusinessProcess::getCreateTime))
.collect(Collectors.toList());
list按某个属性分组为map,key就是属性值,value是对应符合条件的list
1
2
// 示例为把list中demandId相同的list为一组
Map<String, List<BusinessProcess>> processGroupByDemandIdMap = childProcesses.stream().collect(Collectors.groupingBy(BusinessProcess::getDemandId));
根据关键字查询列表,关键字对应多个属性
1
2
3
4
5
6
7
8
9
// 示例为searchKeyWord对应userCode、userName、loginAccount3个字段,匹配上任何一个字段均满足条件的情况
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
// set表示要更新的字段,eq表示where条件后面的字段
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(","));
Author: Aaron
Link: https://xjsir.cn/2023/07/26/Java8stream流高级用法/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.