id pid 形成树状结构找幺儿寻爸爸 流操作实现和递归操作实现(最好不用,效率十分低)

递归处理

@Override
    public List<PmsProductCategory> listWithChildren() {
    
    
        List<PmsProductCategory> list = categoryMapper.listWithChildren();
        List<PmsProductCategory> childMenus = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
    
    
            PmsProductCategory currentMenu = list.get(i);
            PmsProductCategory menu = new PmsProductCategory();
            BeanUtils.copyProperties(currentMenu,menu);
            menu.setChildren(getChildCategory(currentMenu.getId()));
            childMenus.add(menu);
        }
        return childMenus;
    }
/**
     * 递归寻找子节点的方法
     * @param id
     * @return
     */
    private List<PmsProductCategory> getChildCategory(Long id){
    
    
        List<PmsProductCategory> childCategoryList = this.list(Wrappers.<PmsProductCategory>lambdaQuery().eq(PmsProductCategory::getParentId,id));
        for (PmsProductCategory category:childCategoryList) {
    
    
            if (category.getParentId() != null) {
    
    
                category.setChildren(getChildCategory(category.getId()));
            }
        }
        return  childCategoryList;
    }

流操作

public class TreeBuilding {
    
    

    /**
     * 将id-pid转为tree结构,单一顶层节点,顶层节点的id和pid不能相同
     * @param pidList id-pid对象的列表
     * @return tree结构对象
     */
    public PmsProductCategory buildTreeSinge(List<PmsProductCategory> pidList){
    
    
        //以pid为Key进行分组存入Map
        Map<Long,List<PmsProductCategory>> pidListMap =
                pidList.stream().collect(Collectors.groupingBy(PmsProductCategory::getParentId));
        pidList.stream().forEach(item->item.setChildren(pidListMap.get(item.getId())));
        //取出顶层节点的对象,本例顶层节点的"PID"为0,注意是PID
        return pidListMap.get(0).get(0);
    }


    //返回值改为List
    public List<PmsProductCategory> buildTree(List<PmsProductCategory> pidList){
    
    
        Map<Long,List<PmsProductCategory>> pidListMap =
                pidList.stream().collect(Collectors.groupingBy(PmsProductCategory::getParentId));
        pidList.forEach(item->item.setChildren(pidListMap.get(item.getId())));
        //返回结果也改为返回顶层节点的list
        return pidListMap.get(0L);
    }


}

业务

@Override
    public List<PmsProductCategory> listWithChildren() {
    
    
        List<PmsProductCategory> list = categoryMapper.listWithChildren();
        TreeBuilding treeBuilding = new TreeBuilding();
        List<PmsProductCategory> productCategoryList = treeBuilding.buildTree(list);
        return productCategoryList;
    }

猜你喜欢

转载自blog.csdn.net/weixin_45528650/article/details/109844178
PID