@Data @TableName("pms_category") public class CategoryEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 分类id */ @TableId private Long catId; /** * 分类名称 */ private String name; /** * 父分类id */ private Long parentCid; /** * 层级 */ private Integer catLevel; /** * 是否显示[0-不显示,1显示] */ @TableLogic(value = "1", delval = "0") private Integer showStatus; /** * 排序 */ private Integer sort; /** * 图标地址 */ private String icon; /** * 计量单位 */ private String productUnit; /** * 商品数量 */ private Integer productCount; @JsonInclude(JsonInclude.Include.NON_EMPTY) @TableField(exist = false) private List<CategoryEntity> children; }
@Override public List<CategoryEntity> listWithTree() { //1、查询出所有分类 List<CategoryEntity> entities = super.baseMapper.selectList(null); //2、组装成父子的树形结构 //2.1)、找到所有一级分类 List<CategoryEntity> levelMenus = entities.stream() .filter(e -> e.getParentCid() == 0) .peek((menu) -> menu.setChildren(getChildrens(menu, entities))) .sorted((menu, menu2) -> { return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()); }) .collect(Collectors.toList()); return levelMenus; } //递归查找所有菜单的子菜单 private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) { return all.stream().filter(categoryEntity -> { return categoryEntity.getParentCid().equals(root.getCatId()); }).peek(categoryEntity -> { //1、找到子菜单(递归) categoryEntity.setChildren(getChildrens(categoryEntity, all)); }).sorted((menu, menu2) -> { //2、菜单的排序 return (menu.getSort() == null ? 0 : menu.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort()); }).collect(Collectors.toList()); }