记录一段代码,用于实现将父子关系list转为tree
/**
* @author: yc
* @des: 名称、id 通用VO
* @date: 2022/5/25 15:24
*/
@Data
public class NameIdVO {
private String id;
private String name;
}
/**
* @author: yc
* @des: 通用联动VO
* @date: 2022/5/25 16:40
*/
@Data
public class LinkVO {
@ApiModelProperty("名称、id")
private NameIdVO nameId;
@ApiModelProperty("子级List")
private List<LinkVO> childList;
}
public void list2tree(){
// 树深度
Integer treeDeep = 3;
// 累加值
Integer count = 1;
List<LinkVO> tree = new ArrayList<>();
List<AppLszsChainDimDO> baseList = chainDimMapper.selectList(new QueryWrapper<AppLszsChainDimDO>().lambda().eq(AppLszsChainDimDO::getVersionFlag, 1));
// 将根节点单独拿出来
List<AppLszsChainDimDO> rootList = baseList.stream().filter(i -> StringUtils.isBlank(i.getParentcode())).collect(Collectors.toList());
List<String> rootIdList = rootList.stream().map(i -> i.getChainId()).collect(Collectors.toList());
// baseList中移除根节点 再分组
baseList = baseList.stream().filter(i -> !rootIdList.contains(i.getChainId())).collect(Collectors.toList());
Map<String, List<AppLszsChainDimDO>> map = baseList.stream().collect(Collectors.groupingBy(i -> i.getParentcode()));
for(AppLszsChainDimDO root : rootList){
LinkVO node = new LinkVO();
NameIdVO nameIdVO = new NameIdVO();
nameIdVO.setId(root.getChainId());
nameIdVO.setName(root.getChainName());
node.setNameId(nameIdVO);
node.setChildList(new ArrayList<>());
setChild(map,node,treeDeep,count);
tree.add(node);
}
System.out.println(JSON.toJSONString(tree));
}
public void setChild(Map<String, List<AppLszsChainDimDO>> baseMap,LinkVO parent,Integer treeDeep,Integer count){
List<AppLszsChainDimDO> childList = baseMap.get(parent.getNameId().getId());
if((count++) > treeDeep){
return;
}
if(null != childList){
parent.setChildList(childList.stream().map(i -> {
LinkVO childVO = new LinkVO();
NameIdVO nameIdVO = new NameIdVO();
nameIdVO.setId(i.getChainId());
nameIdVO.setName(i.getChainName());
childVO.setNameId(nameIdVO);
childVO.setChildList(new ArrayList<>());
return childVO;
}).collect(Collectors.toList()));
for(LinkVO parentVO : parent.getChildList()){
setChild(baseMap,parentVO,treeDeep,count);
}
}
}