1.实体类
import java.util.List;
public class Node {
private String id;
private String pid;
private String name;
private boolean disabled;
private List<Node> list;
public Node(String id, String pid, String name,boolean disabled) {
this.id = id;
this.pid = pid;
this.name = name;
this.disabled = disabled;
}
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 String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isDisabled() {
return disabled;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public List<Node> getList() {
return list;
}
public void setList(List<Node> list) {
this.list = list;
}
}
2. 工具类
import java.util.ArrayList;
import java.util.List;
public class NodeUtil {
public static Node packageTree(List<Node> nodeList, Node rootNode) {
if (nodeList != null && nodeList.size() > 0) {
nodeList.forEach(node -> judgeObj(node, rootNode));
if (rootNode.getList() != null && rootNode.getList().size() > 0) {
rootNode.getList().forEach(r -> packageTree(nodeList, r));
}
}
return rootNode;
}
public static void judgeObj(Node node, Node rootNode) {
List<Node> children = rootNode.getList();
if (children == null) {
children = new ArrayList<>();
}
if (node != null && !node.getPid().isEmpty() && rootNode.getId().equalsIgnoreCase(node.getPid())) {
children.add(node);
rootNode.setList(children);
}
}
}
3. 调用
封装数据:
//封装数据
List<Node> listNode = new ArrayList<>();
listNode.add(new Node(id, pid, name, false));
//转换为tree
List<Node> resultList = new ArrayList<>();
listNode.stream().filter(node -> node.getPid().isEmpty()).collect(Collectors.toList())
.forEach(r -> {
Node areaTreeResult = NodeUtil.packageTree(listNode, r);
resultList.add(areaTreeResult);
});
resultList.get(0).setDisabled(true);