javalist实现树形结构

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

javalist实现树形结构1.javabean

import java.util.List;

public class TreeNode {

private String id;

private String parentId;

private String name;

private List<TreeNode> children;

public TreeNode(String id, String name, String parentId) {

this.id = id;

this.parentId = parentId;

= name;

}

public TreeNode(String id, String name, TreeNode parent) {

this.id = id;

this.parentId = parent.getId();

= name;

}

public String getParentId() {

return parentId;

}

public void setParentId(String parentId) {

this.parentId = parentId;

}

public String getName() {

return name;

}

public void setName(String name) {

= name;

}

public String getId() {

return id;

}

public void setId(String id) {

this.id = id;

}

public List<TreeNode> getChildren() {

return children;

}

public void setChildren(List<TreeNode> children) {

this.children = children;

}

@Override

public String toString() {

return "TreeNode{" +

"id='" + id + '\'' +

", parentId='" + parentId + '\'' +

", name='" + name + '\'' +

", children=" + children +

'}';

}

}

2.⽅法

import java.util.ArrayList;

import java.util.List;

public class TreeBuilder {

/**

* 两层循环实现建树

* @param treeNodes 传⼊的树节点列表

* @return

*/

public static List<TreeNode> bulid(List<TreeNode> treeNodes) {

List<TreeNode> trees = new ArrayList<TreeNode>();

for (TreeNode treeNode : treeNodes) {

if ("0".equals(treeNode.getParentId())) {

trees.add(treeNode);

}

for (TreeNode it : treeNodes) {

if (it.getParentId() == treeNode.getId()) {

if (treeNode.getChildren() == null) {

treeNode.setChildren(new ArrayList<TreeNode>());

}

treeNode.getChildren().add(it);

}

}

}

return trees;

}

/**

* 使⽤递归⽅法建树

* @param treeNodes

* @return

*/

public static List<TreeNode> buildByRecursive(List<TreeNode> treeNodes) {

List<TreeNode> trees = new ArrayList<TreeNode>();

for (TreeNode treeNode : treeNodes) {

if ("0".equals(treeNode.getParentId())) {

trees.add(findChildren(treeNode,treeNodes));

}

}

return trees;

}

/**

* 递归查找⼦节点

* @param treeNodes

* @return

*/

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 ArrayList<TreeNode>());

}

treeNode.getChildren().add(findChildren(it,treeNodes));

}

相关文档
最新文档