public List<PmsCategory> listWithTree() {
// 1、查出所有分类数据
List<PmsCategory> categories = baseMapper.selectList(null);
// 2、将查出的数据组装成父子结构,首先过滤出一级分类,然后对每个一级分类进行子分类组装,此处注意数据库中一定不能有ParentCid为空的数据,不然会报空指针
return categories.stream().filter(category -> category.getParentCid() == 0)
//peek 的作用类似forEach() ,不过peek返回的是stream流本身,而forEach则会终结流操作
.peek(category -> category.setChildren(getChildren(category, categories)))
// 使用Comparator比较器时只需要传入比较的对象即可
.sorted(Comparator.comparingInt(o -> (o.getSort() == null ? 0 : o.getSort())))
.collect(Collectors.toList());
}
// 从所有菜单中查出当前菜单的子菜单,层层递归
private List<PmsCategory> getChildren(PmsCategory target, List<PmsCategory> source) {
return source.stream().filter(category -> Objects.equals(category.getParentCid(), target.getCatId()))
.peek(category -> category.setChildren(getChildren(category, source)))
.sorted(Comparator.comparingInt(o -> (o.getSort() == null ? 0 : o.getSort())))
.collect(Collectors.toList());
}
查询出所有菜单并将其组装成父子结构
最新推荐文章于 2024-01-28 02:27:10 发布