List組裝樹形結構資料,子節點去重!
阿新 • • 發佈:2018-12-21
- TreeNode實體
public class TreeNode { private String id; private String parentId; private HashSet<TreeNode> children; public TreeNode(String id, String parentId) { this.id = id; this.parentId = parentId; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public String getId() { return id; } public void setId(String id) { this.id = id; } public HashSet<TreeNode> getChildren() { return children; } public void setChildren(HashSet<TreeNode> children) { this.children = children; } }
- 使用遞迴建造樹結構
/** * 使用遞迴方法建樹 * @param treeNodes * @return */ public static List<TreeNode> buildTree(List<TreeNode> treeNodes) { List<TreeNode> trees = new ArrayList<>(); for (TreeNode treeNode : treeNodes) { if ("0".equals(treeNode.getParentId())) { trees.add(findChildren(treeNode,treeNodes)); } } return trees; } public static TreeNode findChildren(TreeNode treeNode,List<TreeNode> treeNodes) { for (TreeNode it : treeNodes) { if(treeNode.getId().equals(it.getParentId())) { if (treeNode.getChildren() == null) { treeNode.setChildren(new HashSet<TreeNode>()); } treeNode.getChildren().add(findChildren(it,treeNodes)); } } return treeNode; }
- 組裝資料
public static List<TreeNode> packageData(){ TreeNode treeNode1 = new TreeNode("1","0"); TreeNode treeNode2 = new TreeNode("2","0"); TreeNode treeNode3 = new TreeNode("3","2"); TreeNode treeNode4 = new TreeNode("4","2"); TreeNode treeNode5 = new TreeNode("5","2"); TreeNode treeNode6 = new TreeNode("6","3"); TreeNode treeNode7 = new TreeNode("7","6"); TreeNode treeNode8 = new TreeNode("8","6"); TreeNode treeNode9 = new TreeNode("9","1"); TreeNode treeNode10 = new TreeNode("10","9"); TreeNode treeNode11 = new TreeNode("11","9"); TreeNode treeNode12 = new TreeNode("12","11"); List<TreeNode> list = new ArrayList<>(); list.add(treeNode1); list.add(treeNode2); list.add(treeNode3); list.add(treeNode4); list.add(treeNode5); list.add(treeNode6); list.add(treeNode7); list.add(treeNode8); list.add(treeNode9); list.add(treeNode10); list.add(treeNode11); list.add(treeNode12); return list; }
- 測試
public static void main(String[] args) {
List<TreeNode> treeNodes = packageData();
List<TreeNode> treeList = TreeBuilder.buildTree(treeNodes);
}
-
小結:
在TreeNode實體中,不要用List 構造子節點,否則會出現重複。