ListBusinessDomainPo List转为Tree结构的对象数组
要将List
public class TreeNode {
    private BusinessDomainPo data;
    private List<TreeNode> children;
    
    // getters and setters
}
然后,可以使用递归的方式将List转换为Tree结构的对象数组:
public List<TreeNode> convertToTree(List<BusinessDomainPo> list) {
    // 创建根节点列表
    List<TreeNode> rootNodes = new ArrayList<>();
    
    // 创建节点映射,用于快速查找已创建的节点
    Map<Long, TreeNode> nodeMap = new HashMap<>();
    
    // 遍历原始列表,创建节点并建立父子关系
    for (BusinessDomainPo po : list) {
        TreeNode node = new TreeNode();
        node.setData(po);
        node.setChildren(new ArrayList<>());
        
        // 将节点添加到映射中
        nodeMap.put(po.getId(), node);
        
        // 如果当前节点是根节点,则直接添加到根节点列表中
        if (po.getParentId() == null) {
            rootNodes.add(node);
        } else {
            // 如果当前节点不是根节点,则将节点添加到父节点的子节点列表中
            TreeNode parentNode = nodeMap.get(po.getParentId());
            parentNode.getChildren().add(node);
        }
    }
    
    return rootNodes;
}
使用示例:
List<BusinessDomainPo> list = new ArrayList<>();
// 假设已经从数据库中查询到了原始数据,并存储在list中
List<TreeNode> treeNodes = convertToTree(list);
// 将原始数据转换为Tree结构的对象数组
注意:上述代码假设BusinessDomainPo类包含id和parentId属性,用于表示节点之间的父子关系。如果实际情况不同,需要根据具体的业务逻辑进行调整
原文地址: https://www.cveoy.top/t/topic/iXmB 著作权归作者所有。请勿转载和采集!