@UtilityClass
public class TreeUtil {
/**
* 构建树
* @param modelTrees
* @return
*/
public <T extends TreeVO<T>> List<T> buildTree(List<T> modelTrees){
if(CollectionUtils.isEmpty(modelTrees)){
return new ArrayList<>();
}
List<T> rootList = modelTrees.stream().filter(e -> e.getPid().equals(0L)).collect(Collectors.toList());
List<T> childList = modelTrees.stream().filter(e -> e.getPid()>0L).collect(Collectors.toList());
rootList.forEach(e->setChildList(e,childList));
return rootList;
}
/**
* 设置树的子节点
* @param treeVO 父节点
* @param trees 待处理列表
*/
public <T extends TreeVO<T>> void setChildList(T treeVO,List<T> trees){
if(CollectionUtils.isEmpty(trees)){
return ;
}
List<T> collect = trees.stream().filter(a -> a.getPid().equals(treeVO.getId())).collect(Collectors.toList());
if(CollectionUtils.isEmpty(collect)){
return ;
}
treeVO.setChildList(collect);
trees.removeAll(collect);
for (T e : treeVO.getChildList()) {
setChildList(e, trees);
}
}
}
@Data
@ToString
public class TreeVO<T> {
public Long id;
public Long pid;
public List<T> childList;
}