1.map.getOrDefault方法是判断当map中不存在某个key时,返回默认值.
public static void main(String[] args) {
EmployDO zhangsan = new EmployDO.Builder().name("张三").sex("男").position("职员").status("在职").age("20").build();
EmployDO lisi = new EmployDO.Builder().name("李四").sex("男").position("职员").status("在职").age("24").build();
EmployDO wangwu = new EmployDO.Builder().name("王五").sex("男").position("职员").status("离职").age("21").build();
EmployDO xiaohua = new EmployDO.Builder().name("小花").sex("女").position("职员").status("离职").age("23").build();
Map<String, EmployDO> map = new HashMap<>();
map.put("zhangsan", zhangsan);
map.put("lisi", lisi);
map.put("wangwu", wangwu);
EmployDO lisi1 = map.getOrDefault("lisi", xiaohua);
System.out.println(JSON.toJSONString(lisi1));// 因为map中存在key值"lisi",所以返回"lisi"对应的value
// {"age":"24","name":"李四","position":"职员","sex":"男","status":"在职"}
EmployDO xiaohua1 = map.getOrDefault("lihua", xiaohua);
System.out.println(JSON.toJSONString(xiaohua1));// 因为map中不存在key值"lihua",所以返回默认value--xiaohua
// {"age":"23","name":"小花","position":"职员","sex":"女","status":"离职"}
}
}
2.list转map方法
List<IboSaasDeviceBasic> iboSaasDeviceBasics = iboSaasDeviceBasicManager.selectBySpaceAndType(controlBasicInfoDTO.getSpaceCode(), controlBasicInfoDTO.getMac(), SessionUtil.getCorpId(),true, Constant.PAD);
Map<String, IboSaasDeviceBasic> mapMac = iboSaasDeviceBasics.stream().collect(Collectors.toMap(IboSaasDeviceBasic::getGlobalMac, Function.identity(), (v1, v2) -> v1));
Map<String, IboSaasDeviceBasic> mapDeviceAlias = iboSaasDeviceBasics.stream().collect(Collectors.toMap(IboSaasDeviceBasic::getDeviceAlias, Function.identity(), (v1, v2) -> v1));
List<String> spaceCodeList = iboSaasDeviceBasics.stream().map(IboSaasDeviceBasic::getSpaceCode).collect(Collectors.toList());
List<IboSaasSpace> iboSaasSpaces = iboSaasSpaceManager.listBySpaceCode(spaceCodeList, SessionUtil.getCorpId());
Map<String, IboSaasSpace> mapSpaceCode = iboSaasSpaces.stream().collect(Collectors.toMap(IboSaasSpace::getSpaceCode, Function.identity(), (v1, v2) -> v1));
List<ControlBasicInfoDO> controlBasicInfoDOS = controlBasicInfoManager.selectControlBasicInfo(SessionUtil.getCorpId());
List<ControlBasicInfoVo> list = new ArrayList<>();
controlBasicInfoDOS.forEach(controlBasicInfoDO -> {
ControlBasicInfoVo vo = BeanUtil.map(controlBasicInfoDO, ControlBasicInfoVo.class);
vo.setSpaceCode(mapMac.getOrDefault(vo.getMac(), new IboSaasDeviceBasic()).getSpaceCode());
vo.setSpaceName(mapSpaceCode.getOrDefault(vo.getSpaceCode(), new IboSaasSpace()).getSpaceName());
vo.setDeviceAlias(mapDeviceAlias.getOrDefault(vo.getMac(),new IboSaasDeviceBasic()).getDeviceAlias());
list.add(vo);
});
IPage<ControlBasicInfoVo> page = PageInfoHelperUtils.newPageByQuery(controlBasicInfoDTO);
return PageInfoHelperUtils.listPage(list,page);