分类递归很多功能都可以遇到的但是如果数据特别大的情况下就会很慢了
- 原代码
List<CategoryEntity> res = entities.stream()// 过滤找出一级分类.filter(categoryEntity -> categoryEntity.getParentCid() == 0)// 处理,给一级菜单递归设置子菜单.peek(menu -> menu.setChildren(getChildless(menu, entities)))// 按sort属性排序.sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());return res;
}
- 优化后
public List<CategoryEntity> listWithLambda() {List<CategoryEntity> entities = new ArrayList<>(baseMapper.selectList(Wrappers.<CategoryEntity>lambdaQuery().orderByDesc(CategoryEntity::getCatId)));Map<Long, List<CategoryEntity>> longListNavigableMap = entities.stream().collect(Collectors.groupingBy(CategoryEntity::getParentCid));List<CategoryEntity> res = entities.stream().peek(entity -> {if (longListNavigableMap.containsKey(entity.getCatId())) {entity.setChildren(longListNavigableMap.get(entity.getCatId()));}}).filter(entity -> entity.getCatLevel() == 1).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());return res;
}