Java將List集合組裝成樹(Tree)樹結構組裝

༒雲竹無心༒發表於2019-01-02

把列表轉換為樹結構

/**
 * 把列表轉換為樹結構
 *
 * @param originalList 原始list資料
 * @param keyName 作為唯一標示的欄位名稱
 * @return 組裝後的集合
 */
public static <T> List<T> getTree(List<T> originalList, String keyName) throws Exception {
    String parentFieldName = "parentId";
    String childrenFieldName = "children";

    // 獲取根節點,即找出父節點為空的物件
    List<T> topList = new ArrayList<>();
    for (int i = 0; i < originalList.size(); i++) {
        T t = originalList.get(i);
        String parentId = BeanUtils.getProperty(t, parentFieldName);
        if (StringUtils.isBlank(parentId)) {
            topList.add(t);
        }
    }

    // 將根節點從原始list移除,減少下次處理資料
    originalList.removeAll(topList);

    // 遞迴封裝樹
    fillTree(topList, originalList, keyName, parentFieldName, childrenFieldName);

    return topList;
}

 

封裝樹

/**
 * 封裝樹
 *
 * @param parentList 要封裝為樹的父物件集合
 * @param originalList 原始list資料
 * @param keyName 作為唯一標示的欄位名稱
 * @param parentFieldName 模型中作為parent欄位名稱
 * @param childrenFieldName 模型中作為children的欄位名稱
 */
public static <T> void fillTree(List<T> parentList, List<T> originalList, String keyName, String parentFieldName, String childrenFieldName) throws Exception {
    for (int i = 0; i < parentList.size(); i++) {
        List<T> children = fillChildren(parentList.get(i), originalList, keyName, parentFieldName, childrenFieldName);
        if (children.isEmpty()) {
            continue;
        }
        originalList.removeAll(children);
        fillTree(children, originalList, keyName, parentFieldName, childrenFieldName);
    }
}

封裝子物件

/**
 * 封裝子物件
 *
 * @param parent 父物件
 * @param originalList 待處理物件集合
 * @param keyName 作為唯一標示的欄位名稱
 * @param parentFieldName 模型中作為parent欄位名稱
 * @param childrenFieldName 模型中作為children的欄位名稱
 */
public static <T> List<T> fillChildren(T parent, List<T> originalList, String keyName, String parentFieldName, String childrenFieldName) throws Exception {
    List<T> childList = new ArrayList<>();
    String parentId = BeanUtils.getProperty(parent, keyName);
    for (int i = 0; i < originalList.size(); i++) {
        T t = originalList.get(i);
        String childParentId = BeanUtils.getProperty(t, parentFieldName);
        if (parentId.equals(childParentId)) {
            childList.add(t);
        }
    }
    if (!childList.isEmpty()) {
        FieldUtils.writeDeclaredField(parent, childrenFieldName, childList, true);
    }
    return childList;
}

 

測試實體類

/**
 * 測試實體類
 */
public class Catalog {

    /**
     * 唯一編號 uuid
     */
    private String id;

    /**
     * 名稱
     */
    private String name;

    /**
     * 父節點id
     */
    private String parentId;

    /**
     * 子節點(資料庫中不存在該欄位,僅用於傳輸資料使用)
     */
    private List<?> children;

    // 省略 get set
}

測試

/**
* 測試 一共有六個Catalog
* 其中:name1下面有三個子節點:name2、name3、name4
*      name2下面有兩個子節點:name5、name6
*/
@Test
public void ListToMap() throws Exception {
    List<Catalog> list = new ArrayList<>();

    Catalog catalog = new Catalog();
    String flowId = randomUUID();
    catalog.setFlowId(flowId);
    catalog.setName("name1");
    list.add(catalog);

    catalog = new Catalog();
    String flowId2 = randomUUID();
    catalog.setFlowId(flowId2);
    catalog.setName("name2");
    catalog.setParentId(flowId);
    list.add(catalog);

    catalog = new Catalog();
    String flowId3 = randomUUID();
    catalog.setFlowId(flowId3);
    catalog.setName("name3");
    catalog.setParentId(flowId);
    list.add(catalog);

    catalog = new Catalog();
    String flowId4 = randomUUID();
    catalog.setFlowId(flowId4);
    catalog.setName("name4");
    catalog.setParentId(flowId);
    list.add(catalog);

    catalog = new Catalog();
    String flowId5 = randomUUID();
    catalog.setFlowId(flowId5);
    catalog.setName("name5");
    catalog.setParentId(flowId2);
    list.add(catalog);

    catalog = new Catalog();
    String flowId6 = randomUUID();
    catalog.setFlowId(flowId6);
    catalog.setName("name6");
    catalog.setParentId(flowId2);
    list.add(catalog);

    List<Catalog> tree = getTree(list, "flowId");
    System.out.println(JSON.toJSONString(tree));

    /* 裝換後輸出json樣式
    [
      {
        "id" : "ee55dafee60d44a3a143bd3623f29aa9",
        "name" : "name1",
        "children" : [
          {
            "id" : "2e049bdb67624054ad989b511f1b7674",
            "parentId" : "ee55dafee60d44a3a143bd3623f29aa9",
            "name" : "name2",
            "children" : [
              {
                "id" : "9292a15c7a5e4983ac03d10c5fe12a14",
                "name" : "name5",
                "parentId" : "2e049bdb67624054ad989b511f1b7674"
              },
              {
                "id" : "6cd9608726a1438682f239b6017680ca",
                "name" : "name6",
                "parentId" : "2e049bdb67624054ad989b511f1b7674"
              }
            ]
          },
          {
            "id" : "98e90c9e23e445f980c4116bd4c83233",
            "name" : "name3",
            "parentId" : "ee55dafee60d44a3a143bd3623f29aa9"
          },
          {
            "id" : "5e67e73c6aef4eb19b63b4789dcc3486",
            "name" : "name4",
            "parentId" : "ee55dafee60d44a3a143bd3623f29aa9"
          }
        ]
      }
    ]
    */
}

protected String randomUUID() {
    return UUID.randomUUID().toString().replace("-", "");
}

相關文章