java实现构造无限层级树形结构

起步

实现一个树形结构,新建一个Tree类,主要包含节点id,父节点 默认0为根节点parentId
节点的名称name,是否存在子节点hasChild

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class Tree{
/**
* 节点id
*/
private String id;
/**
* 父节点 默认0为根节点
*/
private String parentId;
/**
* 节点名称
*/
private String name;
/**
* 是否有子节点
*/
private boolean hasChild;

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 String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public boolean isHasChild() {
return hasChild;
}

public void setHasChild(boolean hasChild) {
this.hasChild = hasChild;
}

public Tree(String id, String parentId, String name) {
this.id = id;
this.parentId = parentId;
this.name = name;
}
}

新建一个构造树形结构的工具类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class TreeUtil {
public static Map mapArray = new LinkedHashMap();

public List tree;
public List list = new ArrayList();

public List treeMenu(List tree) {
this.tree = tree;
for (Tree treeNode : tree) {
Map mapArr = new LinkedHashMap();
if (treeNode.getParentId().equals("0")) {
setTreeMap(mapArr, treeNode);
list.add(mapArr);
}
}
return list;
}

public List child(String id) {
List lists = new ArrayList();
for (Tree a : tree) {
Map childArray = new LinkedHashMap();
if (a.getParentId().equals(id)) {
setTreeMap(childArray, a);
lists.add(childArray);
}
}
return lists;
}

private void setTreeMap(Map mapArr, Tree treeNode) {
mapArr.put("id", treeNode.getId());
mapArr.put("name", treeNode.getName());
mapArr.put("parentId", treeNode.getParentId());
List children = child(treeNode.getId());
if (children.size() > 0) {
mapArr.put("hasChild", true);
} else {
mapArr.put("hasChildren", false);
}
mapArr.put("children", child(treeNode.getId()));
}
}

你可能感兴趣的:(java实现构造无限层级树形结构)