java8之list和map集合转换

来源:互联网 发布:软件协会网站 编辑:程序博客网 时间:2024/06/05 19:28
将一个list集合转换城Map集合
List<BizUserClass> bizUserClassList = iBizUserClassApiService.findBizUserClassList();


Map<String, String> bizUserClassMap = bizUserClassList.stream()
.collect(Collectors.toMap((p) -> p.getId(), (p) -> p.getName()));


// filter 先按条件进行过滤,然后循环读取list集合,对其中的元素设置属性,forEach 方法可以给一个具体的方法
authList.stream().filter(auth -> auth.getOrg().getOrgType() == OrgType.城市).forEach(auth -> {
Integer cityId = auth.getOrg().getId();
CityPO cityPO = cityPOMapper.selectByPrimaryKey(cityId);
if (cityPO != null) {
CityOrg cityOrg = cityPO.convertPOToCityModel();
auth.setOrg(cityOrg);
}

});

//将list集合先转换为Set集合,然后再转换为Map集合
List<Warehouse> warehouseList = modelPageList.getDataList();
// 这里得到了城市ID的集合
Set<Integer> cityIds = warehouseList.stream().map(p -> p.getCityId())
.collect(Collectors.toSet());
List<Integer> cityIdList = cityIds.stream().collect(Collectors.toList());
// 通过城市ID集合得到了城市对象的Map
Map<Integer, CityOrg> cityMap = iCityService.getCityListByIdList(cityIdList);


public Map<Integer, CityOrg> getCityListByIdList(List<Integer> cityIds) {
return cityIds.stream().distinct().collect(Collectors.toMap(p -> p, this::getCity));
}