在java实际项目开发过程中,存在大量的数据结构需要来回转换,可以使用stream()来简化操作
例如存在如下数据集合(持续更新常用操作):
List<SysNoticeDTO> noticeOldList = noticeService.dynamicSelectNoticeList(diyQuery);
1.单个属性集合:List<Obj>转List<Field>
List<String> nameList = noticeOldList.stream()
.map(SysNoticeDTO::getStationName).collect(Collectors.toList());
2.map对象转换:List<Obj>转Map<Obj>
Map<Long, SysNoticeDTO> dtoOldMap = noticeOldList.stream()
.collect(Collectors.toMap(SysNoticeDTO::getOperateId,
Function.identity(),(key1,key2) -> key2));
3.数据分组转换: List<Obj>转Map<List<obj>>
Map<Long, List<SysNoticeDTO>> dtoOldMapList = noticeOldList.stream()
.collect(Collectors.groupingBy(SysNoticeDTO::getOperateId));
4.过滤筛选符合要求的数据集:List<Obj>转List<RequireObj>
List<SysNoticeDTO> dtoListReQuire = noticeOldList.stream()
.filter(e -> ((e.getReadStatus().intValue() == 1)
&& "0".equals(e.getDelFlag())
)).collect(Collectors.toList())
5.配合Lambda表达式动态设置List<Obj>属性:
注意:返回值为void
noticeOldList.stream().forEach(e->{
e.setNoticeTitle("Hello");
e.setStatus(0);
e.setCreateTime(new Date());
});
6.通过自定义字段或者单属性排序
//单属性(Collections.sort方法仅支持List集合,且返回值为void)
List<String> overviewBarNameList = new ArrayList<>(overviewBarCountMap.keySet());
Collections.sort(overviewBarNameList);
//升序
originalList.stream()
.sorted(Comparator.comparing(ScrpPlanInputMonthImportInfo::getNoNum))
.collect(Collectors.toList());
//降序
originalList.stream()
.sorted(Comparator.comparing(ScrpPlanInputMonthImportInfo::getNoNum).reversed())
.collect(Collectors.toList());
7.通过自定义字段求和
//BigDecimal求和
BigDecimal decimalSum = staTypeCountObjMap.get(str).stream()
.map(ScrpPlanInputMonthImportInfo::getSpimdSum)
.reduce(BigDecimal.ZERO, BigDecimal::add);
//其他基本类型求和
int intSum = originalList.stream()
.mapToInt(ScrpPlanInputMonthImportInfo::getNoNum).sum();
8.通过自定义分组过滤统计
//先过滤再分组
Map<String, List<BaseReleaseEntity>> baseReleaseMap =
releaseList.stream().filter(e -> StringUtils.isNotEmpty(e.getStageid()))
.collect(Collectors.groupingBy(BaseReleaseEntity::getStageid));
//先过滤再统计
int applySum = (int) applyList.stream()
.filter(e->"2".equals(e.getType())).count();
9.其他的特殊用法
eg1:支持数据转换,精准匹配集合中的数据,例如如下
String strArray = "1,2,5,45,22,52,7";
System.out.println("原始数据:"+ strArray);
int[] toArray = Arrays.stream(strArray.trim().split(","))
.mapToInt(Integer::parseInt).toArray();
System.out.println("需要匹配的数据:"+ JSON.toJSONString(toArray));
boolean flag = IntStream.of(toArray).anyMatch(x -> x == 2);
if(flag){
System.out.println("匹配数据成功");
}else {
System.out.println("匹配数据失败");
}