To transform a List of Lists of BusinessDomainPo objects into a Tree structure (List), follow these steps:

  1. Create an empty List for the tree: This list will store the converted tree structure.
  2. Iterate through the original List<List>: For each BusinessDomainPo object within the nested lists:
    • Retrieve the parent ID: Assuming the parent ID is stored in the 'parentId' field of the BusinessDomainPo object.
    • Search for the parent node in the tree list:
      • If the parent node with the matching 'parentId' is found, add the current BusinessDomainPo object as a child to that parent node.
      • If the parent node is not found, create a new BusinessDomainPo object and add it to the tree list.
  3. Return the converted tree list: The resulting List represents the hierarchical tree structure.

Here's an example code implementation in Java:

public List<BusinessDomainPo> convertToTree(List<List<BusinessDomainPo>> listList) {
    List<BusinessDomainPo> treeList = new ArrayList<>();

    for (List<BusinessDomainPo> list : listList) {
        for (BusinessDomainPo businessDomainPo : list) {
            String parentId = businessDomainPo.getParentId();
            BusinessDomainPo parent = findParent(treeList, parentId);
            if (parent != null) {
                parent.getChildren().add(businessDomainPo);
            } else {
                treeList.add(businessDomainPo);
            }
        }
    }

    return treeList;
}

private BusinessDomainPo findParent(List<BusinessDomainPo> treeList, String parentId) {
    for (BusinessDomainPo businessDomainPo : treeList) {
        if (businessDomainPo.getId().equals(parentId)) {
            return businessDomainPo;
        }
        BusinessDomainPo parent = findParent(businessDomainPo.getChildren(), parentId);
        if (parent != null) {
            return parent;
        }
    }
    return null;
}

Note that the above code assumes the BusinessDomainPo class has the following properties and methods:

public class BusinessDomainPo {
    private String id;
    private String parentId;
    private List<BusinessDomainPo> children;

    // 省略构造方法和其他方法

    // getter和setter方法
    // ...
}

With this code, you can efficiently convert a List of Lists of BusinessDomainPo objects into a Tree structure, representing hierarchical relationships among your data.

Java List to Tree Conversion: Efficiently Transform List<List<BusinessDomainPo>> to Tree Structure

原文地址: https://www.cveoy.top/t/topic/qDlO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录