Java 实现树结构计算各个节点数的和

private List<ESHomeSearchTreeVo> tree(List<ESHomeSearchTreeVo> allList){

        // 构建的整个树数据
        List<TreeNode<String>> treeNodeList = allList.stream().map(x -> {
            Map<String, Object> extraMap = new HashMap<>();
            extraMap.put("num", x.getNum());
            // 单个树数据构建
            TreeNode<String> treeNode = new TreeNode<String>()
                    .setId(String.valueOf(x.getId())) // 主键
                    .setParentId(String.valueOf(x.getParentId())) // 父节点ID
                    .setName(x.getName()) // 名称
                    .setExtra(extraMap);
            return treeNode;
        }).collect(Collectors.toList());

        // 配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名(修改默认名称)
        treeNodeConfig.setChildrenKey("children");
        // 最大递归深度
        treeNodeConfig.setDeep(10);

        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(treeNodeList, "0", treeNodeConfig,
                (treeNode, tree) -> {
                    // 给树节点赋值(还能set 父 或子节点树)
                    tree.setId(treeNode.getId());
                    tree.setParentId(treeNode.getParentId());
                    tree.setName(treeNode.getName());
                    tree.putExtra("num", treeNode.getExtra().getOrDefault("num", null));
                });

        treeNodes.forEach(this::warehouse);
        List<ESHomeSearchTreeVo> esHomeSearchTreeVos = JSONUtil.toList(JSONUtil.toJsonStr(treeNodes), ESHomeSearchTreeVo.class);

        return esHomeSearchTreeVos;
    }

计算每个节点的值

private void warehouse(Tree<String> e) {
        // 如果没有子节点返回自己
        if (e.getChildren() == null) {
            e.putExtra("num", e.get("num"));
            return;
        }
        // 有子节点的话进行相应处理
        e.getChildren().forEach(this::warehouse);
        int num = e.getChildren().stream().mapToInt(m -> MapUtil.getInt(m, "num")).sum();
        e.putExtra("num", num);
    }

结果展示:
Java 实现树结构计算各个节点数的和_第1张图片

你可能感兴趣的:(java,开发语言)