当前位置: 首页 > article >正文

java将list转成树结构

首先是实体类

public class DwdCusPtlSelectDto {
	//id
    private String key;
    //值
    private String value;
    //中文名
    private String title;
    private List<DwdCusPtlSelectDto> children;
    private String parentId;
    public void addChild(DwdCusPtlSelectDto child) {
        if(this.children == null){
            this.children = new LinkedList<>();
        }
        this.children.add(child);
    }
}

方法

private List<DwdCusPtlSelectDto> rulesToTree(List<DwdCusPtlSelectDto> assetRules) {
        List<DwdCusPtlSelectDto> list = new LinkedList<>();
        Map<String, DwdCusPtlSelectDto> nodeMap = new HashMap<>();

        // 将所有节点放入Map中,方便后续查找
        for (DwdCusPtlSelectDto node : assetRules) {
            nodeMap.put(node.getKey(), node);
        }
		
		//不知道为啥概率性出现重复结点,没办法就拿set判断下
        Set<String> set = new HashSet<>();

        // 构建树结构
        for (DwdCusPtlSelectDto node : assetRules) {
            if ("all".equals(node.getParentId())) {
                list.add(node);
                // 找到根节点
            } else {
                DwdCusPtlSelectDto parentNode = nodeMap.get(node.getParentId());
                if (parentNode != null&&!set.contains(node.getKey())) {
                    parentNode.addChild(node);
                    set.add(node.getKey());
                }
            }
        }
        return list;

    }

如果有老哥知道为啥会概率醒出现重复结点问题,可以评论告诉我一下


http://www.kler.cn/a/536139.html

相关文章:

  • 【Elasticsearch】allow_no_indices
  • 基于RTOS的STM32游戏机
  • 新型智慧城市建设方案-1
  • Page Assist - 本地Deepseek模型 Web UI 的安装和使用
  • Got socket exception during request. It might be caused by SSL misconfiguration
  • 深度探索DeepSeek-R1:AI大模型的本地应用与个人知识库构建
  • 劳务报酬所得税
  • DeepSeek辅助段落扩写的能力怎么样?
  • 【C++】C++11
  • RAID独立硬盘冗余阵列
  • 11.PPT:世界动物日【25】
  • 【vLLM 学习】使用 CPU 安装
  • leetcode_78子集
  • HTML5 新特性有哪些?
  • 02DevOps基础环境准备
  • 人工智能应用实例-自动驾驶
  • docker安装es及分词器ik
  • react 函数组件怎么使用生命周期函数
  • 高校体育场微信小程序管理系统(源码 +文档)
  • Mysql中存储引擎各种介绍以及应用场景、优缺点
  • Android Studio:相对布局 RelativeLayout
  • 【论文阅读】On the Security of “VOSA“
  • tmux 终端复用器
  • Rust 语言:变革关键任务软件的新力量
  • java中equals和hashCode为什么要一起重写
  • 探索Deepseek核心模型:AI领域的新星