用stream流将list转为map
1、将list转为Map<Long, List>
按照spaceId分组,spaceId相同的为一组数据:
List<BasEvaluationPriceResultDto> list = new ArrayList();
Map<Long, List<BasEvaluationPriceResultDto>> priceResultDtoMap = list.stream().collect(Collectors.groupingBy(BasEvaluationPriceResultDto::getSpaceId));
2、将list转为Map<Long, E>
以id为key,数据为value
List<BasProject> list = new ArrayList();
Map<Long, BasProject> mapBasProject = list.stream().collect(Collectors.toMap(BasProject::getId, Function.identity()));
补充:
Function.identity() 源码:
static <T> Function<T, T> identity() {
return t -> t;
}
Function.identity()的实现其实就是等价于形如 t->t 形式的Lambda表达式。可以让代码更加优雅化。
3、将list转为List
将id收集为一个list
List<BasSpacePackage> list = new ArrayList();
List<Long> idList = list.stream().map(BasSpacePackage::getId).collect(Collectors.toList());
将listlist转为Map<String, E>
// 查询已租面积
List rentedAreaList = homeDao.getRentedAreaList(projectIdList,date,Arrays.asList(HomeConstant.LINE_TYPE_1001,HomeConstant.LINE_TYPE_1002));
// 进行转换
Map<String, ProjectLineAreaVo> rentedAreaMap = new HashMap<>();
if(CollectionUtils.isNotEmpty(rentedAreaList)){
rentedAreaMap = rentedAreaList.stream().collect(Collectors.toMap(m -> m.getProjectId() + “_” + m.getLineType(), t -> t));
}
将多个字段拼接到一起作为key