JAVA父子表转Tree

@UtilityClass
public class TreeUtil {
    /**
     * 构建树
     * @param modelTrees
     * @return
     */
    public > List buildTree(List modelTrees){
        if(CollectionUtils.isEmpty(modelTrees)){
            return new ArrayList<>();
        }
        List rootList = modelTrees.stream().filter(e -> e.getPid().equals(0L)).collect(Collectors.toList());
        List childList = modelTrees.stream().filter(e -> e.getPid()>0L).collect(Collectors.toList());
        rootList.forEach(e->setChildList(e,childList));
        return rootList;
    }

    /**
     * 设置树的子节点
     * @param treeVO 父节点
     * @param trees 待处理列表
     */
    public > void setChildList(T treeVO,List trees){
        if(CollectionUtils.isEmpty(trees)){
            return ;
        }
        List 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 {
    public Long id;
    public Long pid;
    public List childList;
}

你可能感兴趣的:(JAVA,java,eureka,开发语言)