借助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行代码搞定树形结构数据更容易看懂
自定义属性
public List<Tree<Integer>> listAllChildren(Integer propertyId, Integer storeId) {
//store_id 为空则默认为1
List<GoodsPropertyVO> allPropertyList = goodsPropertyMapper.listAllChildrenByStoreId(storeId == null ? 1 : storeId);
List<GoodsPropertyVO> goodsPropertyVOList = allPropertyList.stream()
.filter(goodsPropertyVO -> goodsPropertyVO.getPropertyId().intValue() != goodsPropertyVO.getParentId())
.collect(Collectors.toList());
TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
treeNodeConfig.setIdKey("propertyId");
treeNodeConfig.setParentIdKey("parentId");
treeNodeConfig.setNameKey("name");
treeNodeConfig.setWeightKey("propertyOrder");
return TreeUtil.build(goodsPropertyVOList, 0, treeNodeConfig, (treeNode, tree) -> {
tree.setId(treeNode.getPropertyId());
tree.setParentId(treeNode.getParentId());
tree.setWeight(treeNode.getPropertyOrder() == null ? 0 : treeNode.getPropertyOrder());
tree.setName(treeNode.getName());
});
不用递归构造树形结构
//step1:查询所有部门数据
List<SysDept> sysDepts = baseMapper.selectList();
//step2:根据父节点分组
Map<Long, List<SysDept>> listMap = sysDepts.parallelStream().collect(Collectors.groupingBy(SysDept::getParentId));
//step3:关键一步,关联子部门,将子部门的List集合经过遍历一层层地放置好,最终会得到完整的部门父子关系List集合
sysDepts.forEach(val -> val.setChildrenNodeList(listMap.get(val.getDeptId())));
//step4:过滤出顶级部门,即所有的子部门数据都归属于一个顶级父Id
List<SysDept> deptTreeList = sysDepts.stream().filter(val -> val.getParentId() == 0L).collect(Collectors.toList());