Java构建树形结构 tree 父子结构

需要JDK 1.8 以上

不说这么多上代码

		
	//下级菜单   所有的子集存储   CategoryEntity 该类自己
	@TableField(exist = false)
	private List<CategoryEntity> children;
public List<CategoryEntity> listWithTree() {
        //1.查出所有对象  baseMapper 是mybatis plus 构建的持久层对象
        List<CategoryEntity> entities = baseMapper.selectList(null);
        //2. 组装成父子分类
        // 查找一级分类  stream 是为集合创建串行流  
        List<CategoryEntity> collect = entities.stream()
                //过滤所有的分类
                .filter((categoryEntity) -> {
                    //返回所有父级ID 等于0的  如果是字符串请使用 equals 判断
                    return categoryEntity.getParentCid().equals("0");
                })
                // 给每个父级的子集赋值  
                .map((menu) -> {
                	//详细见 getChildrens() 方法  menu 当前父级对象  entities 为所有的对象
                    menu.setChildren(getChildrens(menu, entities));
                    return menu;
                })
                //排序  数字小的排前面
                .sorted((menu1, menu2) -> {
                            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                        }
                )
                //搜集 List
                .collect(Collectors.toList());
        return collect;
    }

		
 /**
     * @param root 当前的元素
     * @param all  所有的元素
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> Children = all.stream()
                //过滤所有的对象
                .filter((categoryEntity) -> {
                    //过滤中的父级ID 等于 root id   
                    return categoryEntity.getParentCid().equals(root.getCatId());
                })
                //在过滤子集 id 有没有 子集 在进行过滤
                .map((categoryEntity) -> {
                            //找到子菜单
                            categoryEntity.setChildren(getChildrens(categoryEntity, all));
                            return categoryEntity;
                        }
                )
                .sorted((menu1, menu2) -> {
                    //菜单的排序
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return Children;
    }

看一下效果

“data”: [
{
“catId”: 1,
“name”: “图书、音像、电子书刊”,
“parentCid”: 0,
“catLevel”: 1,
“showStatus”: 1,
“sort”: 0,
“icon”: null,
“productUnit”: null,
“productCount”: 0,
“children”: [
{
“catId”: 22,
“name”: “电子书刊”,
“parentCid”: 1,
“catLevel”: 2,
“showStatus”: 1,
“sort”: 0,
“icon”: null,
“productUnit”: null,
“productCount”: 0,
“children”: [
{
“catId”: 165,
“name”: “电子书”,
“parentCid”: 22,
“catLevel”: 3,
“showStatus”: 1,
“sort”: 0,
“icon”: null,
“productUnit”: null,
“productCount”: 0,
“children”: []
},


版权声明:本文为weixin_45029961原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。