当前位置:网站首页>部门树递归实现

部门树递归实现

2022-07-06 11:38:00 linsa_pursuer

1.Department实体类

import lombok.Data;

import java.util.List;

@Data
public class Department {
String id;
String parentId;
List<Department> children;
}
2.测试类
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Test {
public static void main(String[] args) throws Exception {
System.out.println(streamToTree(addList(), "000000"));
}

public static List<Department> streamToTree(List<Department> treeList, String parentId) {
return treeList.stream()
// 过滤父节点
.filter(parent -> parent.getParentId().equals(parentId))
// 把父节点children递归赋值成为子节点
.map(child -> {
child.setChildren(streamToTree(treeList, child.getId()));
return child;
}).collect(Collectors.toList());
}

private static List<Department> addList(){
List<Department> list = new ArrayList<Department>();
Department departmentOne = new Department();
departmentOne.setParentId("000000");
departmentOne.setId("111111");
list.add(departmentOne);
Department departmentOne1 = new Department();
departmentOne1.setParentId("111111");
departmentOne1.setId("111222");
list.add(departmentOne1);
Department departmentOne2 = new Department();
departmentOne2.setParentId("111111");
departmentOne2.setId("111333");
list.add(departmentOne2);
Department departmentTwo = new Department();
departmentTwo.setParentId("000000");
departmentTwo.setId("222222");
list.add(departmentTwo);
Department departmentTwo1 = new Department();
departmentTwo1.setParentId("222222");
departmentTwo1.setId("222111");
list.add(departmentTwo1);
return list;
}
}
原网站

版权声明
本文为[linsa_pursuer]所创,转载请带上原文链接,感谢
https://blog.csdn.net/linsa_pursuer/article/details/125608485

随机推荐