借助hutool的Tree和TreeNode数据结构,快速构建树形集合
/**
* 返回树形菜单集合
* @return 树形菜单
*/
@GetMapping(value = "/tree")
public R listDeptTrees() {
return R.ok(sysDeptService.listDeptTrees());
}
/**
* 查询全部部门树
* @return 树
*/
@Override
public List<Tree<Integer>> listDeptTrees() {
return getDeptTree(this.list(Wrappers.emptyWrapper()));
}
/**
* 构建部门树
* @param depts 部门
* @return
*/
private List<Tree<Integer>> getDeptTree(List<SysDept> depts) {
List<TreeNode<Integer>> collect = depts.stream()
.filter(dept -> dept.getDeptId().intValue() != dept.getParentId())
.sorted(Comparator.comparingInt(SysDept::getSort))
.map(dept -> {
TreeNode<Integer> treeNode = new TreeNode<>();
treeNode.setId(dept.getDeptId());
treeNode.setParentId(dept.getParentId());
treeNode.setName(dept.getName());
return treeNode;
}).collect(Collectors.toList());
return TreeUtil.build(collect, 0);
}
这种方法比10行代码搞定树形结构数据更容易看懂