Lambda表达式Stream流的用法示例
1、使用简单示例:
@Override
public List<CategoryEntity> listWithTree() {
//1、查询所有的分类数据
List<CategoryEntity> entities = categoryDao.selectList(null);
//2、组装成父子的树形结构
//2.1、找到所有的一级分类
//List<CategoryEntity> parentCollect = entities.stream().filter(CategoryEntity -> CategoryEntity.getParentCid() == 0).collect(Collectors.toList());
List<CategoryEntity> collect = entities.stream().filter(s -> {
return s.getParentCid() == 0;
}).collect(Collectors.toList());
return collect;
}
2.1、元素判空,避免空指针:
List<FtqDTO> list = environmentMonitoringService.queryElevatorStatus(stationId,regionName,deviceType,deviceName);
//判断设备是否在线
List<FtqDTO> collect = list.stream().filter(s-> {
boolean isNotNull= false;
if(s.getModifyTime() != null) {
isNotNull = deviceOnLine.isIn24H(s.getModifyTime());
}
return isNotNull;
}).collect(Collectors.toList());
2.2、元素判空,避免空指针:
List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
skuImagesEntity.setSkuId(skuId);
skuImagesEntity.setImgUrl(img.getImgUrl());
skuImagesEntity.setDefaultImg(img.getDefaultImg());
return skuImagesEntity;
}).filter(entity -> {
//返回true就是需要,false就是剔除
return !StringUtils.isEmpty(entity.getImgUrl());
}).collect(Collectors.toList());

浙公网安备 33010602011771号