创建返回实体类
@Data
public class Node {
private String id;
private String name;
private String pid;
private List<Node> children;
public Node(String id, String name, String pid) {
this.id = id;
this.name = name;
this.pid = pid;
}
}
stream 转 树形方法
public static List<NodeVO> streamToTree(List<NodeVO> treeList, String parentId) {
List<NodeVO> list = treeList.stream()
.filter(parent -> parent.getPid().equals(parentId))
.map(child -> {
child.setChildren(streamToTree(treeList,child.getId()));
return child;
}).collect(Collectors.toList());
return list;
}
双重 for 转 树形方法
public static List<Node> twoForToTree(List<Node> list, String parentId) {
List<Node> treeList = new ArrayList<Node>();
for (Node tree : list) {
if (parentId.equals(tree.getPid())) {
treeList.add(tree);
}
for (Node treeNode : list) {
if (treeNode.getPid().equals(tree.getId())) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<Node>());
}
tree.getChildren().add(treeNode);
}
}
}
return treeList;
}
递归 转 树形方法
public static List<Node> recursionToTree(List<Node> list, String parentId) {
List<Node> treeList = new ArrayList<Node>();
for (Node tree : list) {
if (parentId.equals(tree.getPid())) {
treeList.add(findChildren(tree, list));
}
}
return treeList;
}
private static Node findChildren(Node tree, List<Node> list) {
for (Node node : list) {
if (node.getPid().equals(tree.getId())) {
if (tree.getChildren() == null) {
tree.setChildren(new ArrayList<Node>());
}
tree.getChildren().add(findChildren(node, list));
}
}
return tree;
}
测试
public static void main(String[] args) {
Node Node1 = new Node("1","山东省","0");
Node Node2 = new Node("2","青岛市","1");
Node Node3 = new Node("3","市北区","2");
Node Node4 = new Node("4","济南市","1");
Node Node5 = new Node("5","浙江省","0");
Node Node6 = new Node("6","杭州市","5");
Node Node7 = new Node("7","西湖区","6");
Node Node8 = new Node("8","龙井村","7");
List<Node> list = new ArrayList<>();
list.add(Node1);
list.add(Node2);
list.add(Node3);
list.add(Node4);
list.add(Node5);
list.add(Node6);
list.add(Node7);
list.add(Node8);
List<Node> nodeList3 = recursionToTree(list,"0");
System.out.println(JSON.toJSONString(nodeList3));
}
以上测试结果展示:
[
{
"children": [
{
"children": [
{
"children": [],
"id": "3",
"name": "市北区",
"pid": "2"
}
],
"id": "2",
"name": "青岛市",
"pid": "1"
},
{
"children": [],
"id": "4",
"name": "济南市",
"pid": "1"
}
],
"id": "1",
"name": "山东省",
"pid": "0"
},
{
"children": [
{
"children": [
{
"children": [],
"id": "7",
"name": "西湖区",
"pid": "6"
}
],
"id": "6",
"name": "杭州市",
"pid": "5"
}
],
"id": "5",
"name": "浙江省",
"pid": "0"
}
]
总结
各位看官可以自行选择自己喜欢的方式,个人觉得Stream比较优雅哈,但是一旦数据错误,排坑比较麻烦,慎选!!!慎选!!!慎选!!!!
|