package com.my.tree;import java.util.List;public class Tree { private String id; // 节点ID private String parentId; // 节点父ID private Listchildren; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public List getChildren() { return children; } public void setChildren(List children) { this.children = children; } }
package com.my.tree;import java.util.ArrayList;import java.util.List;public class TreeUtils { public static ListformatTree(List list) { List nodeList = new ArrayList (); for (Tree node1 : list) { boolean mark = false; for (Tree node2 : list) { if (node1.getParentId() != null && node1.getParentId().equals(node2.getId())) { mark = true; if (node2.getChildren() == null) { node2.setChildren(new ArrayList ()); } node2.getChildren().add(node1); break; } } if (!mark) { nodeList.add(node1); } } return nodeList; } }