1第一种写法
//定义一级分类 id -> 二级分类列表
Map<String,List<CatResponseVO>> catResponseVOListMap = new HashMap<>();
//循环分类关联信息
for (IndexCatPO indexCatPO : indexCatPOList) {
CatResponseVO catResponseVO = new CatResponseVO();
if (catPOMap.containsKey(indexCatPO.getSlaveCatId())){
CatPO catPO = catPOMap.get(indexCatPO.getSlaveCatId());
catResponseVO.setCatName(catPO.getCatName());
catResponseVO.setCatCode(catPO.getCatCode());
}
List<CatResponseVO> catResponseVOList = new ArrayList<>();
//判断是否存在父级id
if (catResponseVOListMap.containsKey(indexCatPO.getMasterCatId())){
catResponseVOList = catResponseVOListMap.get(indexCatPO.getMasterCatId());
}
//判断二级分类信息是否为空
if(!ObjectUtils.isEmpty(catResponseVO)){
catResponseVOList.add(catResponseVO);
}
catResponseVOListMap.put(indexCatPO.getMasterCatId(),catResponseVOList);
}
//遍历一级分类
for (CatPO typePO : typePOList) {
NavigationResponseVO typeResponseVO = new NavigationResponseVO();
typeResponseVO.setTypeCode(typePO.getCatCode());
typeResponseVO.setTypeName(typePO.getCatName());
if (targetIdImage.containsKey(typePO.getId())){
//取一张图片
typeResponseVO.setImagePath(targetIdImage.get(typePO.getId()).get(0));
}else {
typeResponseVO.setImagePath("");
}
if (catResponseVOListMap.containsKey(typePO.getId())){
typeResponseVO.setCatList(catResponseVOListMap.getOrDefault(typePO.getId(),new ArrayList<>()));
}
navigationResponseVOList.add(typeResponseVO);
}
2.第二种写法
//获取一级类目id->二级类目id列表
Map<String, List<String>> slaveCatIdMap = indexCatPOList.stream().collect(Collectors.groupingBy(IndexCatPO::getMasterCatId, Collectors.mapping(IndexCatPO::getSlaveCatId, Collectors.toList())));
//封装数据
for (CatPO typePO : typePOList) {
NavigationResponseVO typeResponseVO = new NavigationResponseVO();
typeResponseVO.setTypeCode(typePO.getCatCode());
typeResponseVO.setTypeName(typePO.getCatName());
if (targetIdImage.containsKey(typePO.getId())){
//取一张图片
typeResponseVO.setImagePath(targetIdImage.get(typePO.getId()).get(0));
}else {
typeResponseVO.setImagePath("");
}
List<CatResponseVO> catList = new ArrayList<>();
if (CollectionUtils.isNotEmpty(catList)){
catList.clear();
}
if (slaveCatIdMap.containsKey(typePO.getId())){
List<String> slaveCatIdList = slaveCatIdMap.get(typePO.getId());
for (String catId : slaveCatIdList) {
if (catPOMap.containsKey(catId)){
CatPO catPO = catPOMap.get(catId);
CatResponseVO catResponseVO = new CatResponseVO();
catResponseVO.setCatCode(catPO.getCatCode());
catResponseVO.setCatName(catPO.getCatName());
catList.add(catResponseVO);
}
}
}
typeResponseVO.setCatList(catList);
navigationResponseVOList.add(typeResponseVO);
}