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
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java树状列表通常是指基于树形结构的数据展示,可以通过递归算法来实现。以下是一个基于递归算法的Java树状列表实现方式: 1. 定义一个节点类Node,用来表示树形结构中的节点,包含节点id、父节点id、节点名称等属性: ``` public class Node { private String id; private String parentId; private String name; private List<Node> children; // getter和setter方法省略 } ``` 2. 定义一个工具类TreeUtil,实现树形结构构建和遍历操作: ``` public class TreeUtil { /** * 构建树形结构 * @param nodeList 节点列表 * @return 根节点列表 */ public static List<Node> buildTree(List<Node> nodeList) { List<Node> rootList = new ArrayList<>(); Map<String, Node> nodeMap = new HashMap<>(); for (Node node : nodeList) { nodeMap.put(node.getId(), node); } for (Node node : nodeList) { String parentId = node.getParentId(); if (parentId == null || "".equals(parentId)) { rootList.add(node); } else { Node parent = nodeMap.get(parentId); if (parent != null) { if (parent.getChildren() == null) { parent.setChildren(new ArrayList<>()); } parent.getChildren().add(node); } } } return rootList; } /** * 遍历树形结构 * @param nodeList 节点列表 */ public static void traverseTree(List<Node> nodeList) { for (Node node : nodeList) { System.out.println(node.getName()); if (node.getChildren() != null) { traverseTree(node.getChildren()); } } } } ``` 3. 在业务层中调用TreeUtil工具类构建树形结构并进行遍历操作: ``` public class DemoService { public void demo() { // 从数据库或文件中获取节点列表 List<Node> nodeList = getNodeListFromDbOrFile(); // 构建树形结构 List<Node> rootList = TreeUtil.buildTree(nodeList); // 遍历树形结构 TreeUtil.traverseTree(rootList); } } ``` 以上是一个基于递归算法的Java树状列表实现方式,具体实现方法可能会因为具体的业务需求而略有不同。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值