Java 樹遞迴
阿新 • • 發佈:2021-11-11
1.實體類studentTree
import lombok.Data; import java.util.List; @Data public class StudentTree { private String id; private String parent; private String name; private String school;
private String type; private List<StudentTree> children; }
2.controller層
@GetMapping("treeList") @ApiOperation(value="樹") public ResponseEntity treeList(String type){ return ResponseEntity.ok(pageHelperService.treeList(type)); }
3.service層
private static final String TREE_ROOT_CODE = "0"; public List<StudentTree> treeList(String type) { List<StudentTree> record = pageHelperMapper.treeList(type); List<StudentTree> treeList = new LinkedList(); for (StudentTree sysDept : record) { if (TREE_ROOT_CODE.equals(sysDept.getParent())) { StudentTree tableHeaderInfo = new StudentTree(); BeanUtils.copyProperties(sysDept,tableHeaderInfo); tableHeaderInfo.setChildren(getChild(sysDept.getId(), record)); treeList.add(tableHeaderInfo); } }return treeList; } private static List<StudentTree> getChild(String code, List<StudentTree> record) { List<StudentTree> childrenList = new LinkedList(); for (StudentTree studentTree : record) { if (code.equals(studentTree.getParent())) { StudentTree tableHeaderInfo = new StudentTree(); BeanUtils.copyProperties(studentTree,tableHeaderInfo); tableHeaderInfo.setChildren(getChild(studentTree.getId(), record)); childrenList.add(tableHeaderInfo); } } return childrenList; }
4.postman進行測試(http://localhost:埠號/page/treeList?type=1)
5.結果
[ { "id":"1", "parent":"0", "name":"11", "school":"111", "type":"1", "children":[ { "id":"6", "parent":"1", "name":"66", "school":"666", "type":"1", "children":[ { "id":"7", "parent":"6", "name":"77", "school":"777", "type":"1", "children":[ { "id":"8", "parent":"7", "name":"88", "school":"888", "type":"1", "children":[] } ] } ] } ] }, { "id":"2", "parent":"0", "name":"22", "school":"222", "type":"1", "children":[] }, { "id":"3", "parent":"0", "name":"33", "school":"333", "type":"1", "children":[] }, { "id":"4", "parent":"0", "name":"44", "school":"444", "type":"1", "children":[] } ]final:不積跬步,無以至千里.不積小流,無以成江海