JAVA构建树状结构

记一下自己在展示树状结构时候的几个写法,一个是确定有几个层级的,用于只有两三个层级的树状结构,写法简单一点。还有就是不确定有几个层级,也可能1个,也可能4个或者更多。

先说一下确定有几个层级的写法

这是需要用的树状结构实体类

	//父级菜单id
    private Long id;
    //父级菜单名称
    private String label;
	//子菜单信息
    private List<TreeSelect> children;

    public TreeSelect() {
    }

    public TreeSelect(XXX  xxx) {
        this.id = xxx.getId();
        this.label = xxx.gexxname();
        this.professorName = xxx.getxxxame();
        this.children = xxx.getChildren().stream().map(TreeSelect::new).collect(Collectors.toList());      
    }

明确几个层级的写法(这里是只有两级),做了两个foreach

//入参的list是查询出来的父级菜单的信息
public List<TreeSelect> treeSelectList(List<XXX> indexInfoList) {
     List<TreeSelect> treeSelectList = new ArrayList<>();
     indexInfoList.stream().forEach(e -> {
     TreeSelect treeSelect = new TreeSelect();
     //设置大类信息
     if (e.getIndexPid() == 0) {
     treeSelect.setId(e.getId());
     treeSelect.setLabel(e.getIndexPname());
     List<TreeSelect> secondTree = new ArrayList<>();
     //根据id查询小类信息
     QueryWrapper<XXX> queryWrapper = new QueryWrapper<IndexInfo>()
     .eq("id", e.getId());
     List<XXX> indexInfos = indexInfoMapper.selectList(queryWrapper);
     //设置小类信息
     indexInfos.stream().forEach(indexInfo -> {
     TreeSelect secondTreeSelect = new TreeSelect();
     secondTreeSelect.setId(indexInfo.getId());
     secondTreeSelect.setLabel(indexInfo.getIndexPname());
     secondTree.add(secondTreeSelect);
     });
     //添加集合
     treeSelect.setChildren(secondTree);
     treeSelectList.add(treeSelect);
     }
     });
     return treeSelectList;
     }

下面是不确定几个层级,递归写法

方法类:


    /**
     * 构建树下拉菜单列表
     * @param indexInfoList
     * @return
     */
    public List<TreeSelect> treeSelectList(List<IndexInfo> indexInfoList) {
        List<IndexInfo> trees = buildIndexTree(indexInfoList);
        return trees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 构建树结构
     * @param indexInfoList
     * @return
     */
    public List<IndexInfo> buildIndexTree(List<IndexInfo> indexInfoList) {
        List<IndexInfo> returnList = new ArrayList<IndexInfo>();
        List<Long> indexList = new ArrayList<Long>();
        //一级菜单设置信息
        for (IndexInfo indexInfo : indexInfoList) {
            indexList.add(indexInfo.getId());
        }
        for (Iterator<IndexInfo> iterator = indexInfoList.iterator(); iterator.hasNext(); ) {
            IndexInfo indexInfo =iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!indexList.contains(indexInfo.getIndexPid())) {
                recursionFn(indexInfoList, indexInfo);
                returnList.add(indexInfo);
            }
        }
        if (returnList.isEmpty()) {
            returnList = indexInfoList;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<IndexInfo> list, IndexInfo t) {
        // 得到子节点列表
        List<IndexInfo> childList = getChildList(list, t);
        t.setChildren(childList);
        for (IndexInfo tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<IndexInfo> getChildList(List<IndexInfo> list, IndexInfo t) {
        List<IndexInfo> tlist = new ArrayList<IndexInfo>();
        Iterator<IndexInfo> it = list.iterator();
        while (it.hasNext()) {
            IndexInfo n = it.next();
            if (StringUtils.isNotNull(n.getIndexPid()) && n.getIndexPid().longValue() == t.getId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<IndexInfo> list, IndexInfo t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }

附上结果:

    "msg": "操作成功",
    "code": 200,
    "data": [
        {
            "id": 1,
            "label": "指标名称1"
            "children": [
                {
                    "id": 4,
                    "label": "指标名称1-1"
                    "children": [
                        {
                            "id": 10,
                            "label": "指标名称1-1-1"
                        },
                        {
                            "id": 11,
                            "label": "指标名称1-1-2"
                        }
                    ]
                },
                {
                    "id": 5,
                    "label": "指标名称1-2"
                }
            ]
        }
    ]
}

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
好的,以下是一个简单的Java构建树形菜单的代码样例: ``` public class TreeNode { private long id; // 节点ID private long parentId; // 父节点ID private String name; // 节点名称 private List<TreeNode> children; // 子节点列表 public TreeNode(long id, long parentId, String name) { this.id = id; this.parentId = parentId; this.name = name; this.children = new ArrayList<>(); } // 添加子节点 public void addChild(TreeNode child) { children.add(child); } // 构建树 public static List<TreeNode> buildTree(List<TreeNode> nodeList) { List<TreeNode> treeList = new ArrayList<>(); // 遍历查找根节点 for (TreeNode node : nodeList) { if (node.parentId == 0) { treeList.add(node); } } // 递归构建子节点 for (TreeNode parentNode : treeList) { buildChildren(parentNode, nodeList); } return treeList; } // 构建子节点 private static void buildChildren(TreeNode parentNode, List<TreeNode> nodeList) { for (TreeNode node : nodeList) { if (node.parentId == parentNode.id) { parentNode.addChild(node); buildChildren(node, nodeList); } } } // getter/setter方法 // ... } // 测试代码 public static void main(String[] args) { // 构建样例节点列表 List<TreeNode> nodeList = new ArrayList<>(); nodeList.add(new TreeNode(1, 0, "A")); nodeList.add(new TreeNode(2, 0, "B")); nodeList.add(new TreeNode(3, 1, "A1")); nodeList.add(new TreeNode(4, 1, "A2")); nodeList.add(new TreeNode(5, 2, "B1")); nodeList.add(new TreeNode(6, 4, "A21")); nodeList.add(new TreeNode(7, 5, "B11")); // 构建树形结构 List<TreeNode> treeList = TreeNode.buildTree(nodeList); // 输出 for (TreeNode node : treeList) { printNode(node, 0); } } // 打印节点 private static void printNode(TreeNode node, int depth) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < depth; i++) { sb.append("\t"); } sb.append(node.name); System.out.println(sb.toString()); for (TreeNode child : node.children) { printNode(child, depth + 1); } } ``` 这段代码可以通过定义 `TreeNode` 类表示树节点,通过 `buildTree()` 方法构建整个树形结构,具体实现时需要先遍历节点数组,找到所有的根节点,然后递归地查找并添加子节点。最后可以根据树形结构进行相关操作,例如通过递归打印节点信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

byte-znnd

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值