当前位置:网站首页>Recursive implementation of department tree

Recursive implementation of department tree

2022-07-06 19:40:00 linsa_ pursuer

1.Department Entity class 

import lombok.Data;

import java.util.List;

@Data
public class Department {
String id;
String parentId;
List<Department> children;
}
2. Test class 
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 nodes 
.filter(parent -> parent.getParentId().equals(parentId))
//  Put the parent node children Recursive assignment becomes a child node 
.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://yzsam.com/2022/187/202207061138426677.html