树形结构
代码
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class treeTest {
// 树形类
static class Node{
private String id;
private String pid;
private String name;
private Set<Node> children;
Node(String id, String pid, String name){
this.id = id;
this.pid = pid;
this.name = name;
}
Node(){}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public Set<Node> getChildren() {
return children;
}
public void setChildren(Set<Node> children) {
this.children = children;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
// 是否有子类
private static List<Node> hasChild(Node type,List<Node> list){
List<Node> cList = new ArrayList<>();
for(Node t :list){
if(type.getId().equals(t.getPid())){
cList.add(t);
}
}
return cList;
}
//是否有父类
private static boolean hasParent(Node type,List<Node> list){
if(type.getPid() == null) return false;
for(Node t :list){
if(type.getPid().equals(t.getId())){
return true;
}
}
return false;
}
// 设值children
private static void setChildren(Node parent, Node children){
if(null == parent.getChildren()){
Set<Node> cs = new HashSet<>();
cs.add(children);
parent.setChildren(cs);
}else {
parent.getChildren().add(children);
}
}
private static void toTree(Node type,List<Node> childrenList,List<Node> list){
for(Node children : childrenList){
List<Node> child = hasChild(children,list);
if(null != child && child.size() > 0){
setChildren(type,children);
toTree(children,child,list);
}else{
setChildren(type,children);
}
}
}
public static void main(String[] args) {
List<Node> dataList = new ArrayList<>();
dataList.add(new Node("1",null,"1"));
dataList.add(new Node("2","1","1-1"));
dataList.add(new Node("3","1","1-2"));
dataList.add(new Node("4","0","2"));
dataList.add(new Node("5","4","2-1"));
dataList.add(new Node("6","2","1-1-1"));
dataList.add(new Node("7","6","1-1-1-1"));
dataList.add(new Node("8","7","1-1-1-1"));
dataList.add(new Node("9","8","1-1-1-1-1"));
List<Node> treeList = new ArrayList<>();
for (Node type : dataList) {
if(!hasParent(type,dataList)){
treeList.add(type);
}
List<Node> children = hasChild(type,dataList);
if(null != children && children.size() > 0){
toTree(type,children,dataList);
}
}
System.out.println(JSON.toJSONString(treeList));
}
}
结果
[{
"children": [{
"children": [{
"children": [{
"children": [{
"children": [{
"id": "9",
"name": "1-1-1-1-1",
"pid": "8"
}],
"id": "8",
"name": "1-1-1-1",
"pid": "7"
}],
"id": "7",
"name": "1-1-1-1",
"pid": "6"
}],
"id": "6",
"name": "1-1-1",
"pid": "2"
}],
"id": "2",
"name": "1-1",
"pid": "1"
}, {
"id": "3",
"name": "1-2",
"pid": "1"
}],
"id": "1",
"name": "1"
}, {
"children": [{
"id": "5",
"name": "2-1",
"pid": "4"
}],
"id": "4",
"name": "2",
"pid": "0"
}]