树型结构列表

时间:2022-07-01 13:19:43
package com.dao;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class TreeNode {


private Long id;


private String text;


private String url;


private String state;


private boolean checked;


private Long parentId;


private Map<String, Object> attributes = new HashMap<String, Object>();


private List<TreeNode> children = new ArrayList<TreeNode>();


public TreeNode(){}
public TreeNode(Long id, String text, Long parentId){
this.id =id;
this.text = text;
this.parentId = parentId;
}
public Long getId() {
return id;
}


public void setId(Long id) {
this.id = id;
}


public String getUrl() {
return url;
}


public void setUrl(String url) {
this.url = url;
}


public Long getParentId() {
return parentId;
}


public void setParentId(Long parentId) {
this.parentId = parentId;
}


public String getText() {
return text;
}


public void setText(String text) {
this.text = text;
}


public String getState() {
return state;
}


public void setState(String state) {
this.state = state;
}


public boolean isChecked() {
return checked;
}


public void setChecked(boolean checked) {
this.checked = checked;
}


public List<TreeNode> getChildren() {
return children;
}


public void setChildren(List<TreeNode> children) {
this.children = children;
}


public Map<String, Object> getAttributes() {
return attributes;
}


public void setAttributes(Map<String, Object> attributes) {
this.attributes = attributes;
}


}


package com.dao;


import java.util.ArrayList;
import java.util.List;


public class TestTreeNode {
public static void main(String[] args) {
List<?> list = digui(ini(), 0L);
System.out.println(list.toArray());
}
public static List<TreeNode>  digui(List<TreeNode> data, Long pid){
List<TreeNode> result = new ArrayList<TreeNode>();
        List<TreeNode> temp = new ArrayList<TreeNode>();
        for (TreeNode node : data) {
if(node.getParentId() == pid){
result.add(node);
temp = digui(data, node.getId());
if(temp.size() > 0){
node.setChildren(temp);
}
}
}
        return result;
    }

public static List<TreeNode> ini(){
List <TreeNode> list = new ArrayList<TreeNode>();
list.add(new TreeNode(1L,"部门",0L));
list.add(new TreeNode(2L,"研发部门",1L));
list.add(new TreeNode(3L,"销售部门",1L));
list.add(new TreeNode(4L,"测试部门",1L));
list.add(new TreeNode(5L,"行政部门",1L));
list.add(new TreeNode(6L,"java部门",2L));
list.add(new TreeNode(7L,"c++部门",2L));
list.add(new TreeNode(8L,"ios部门",2L));
return list;
}
}