如何高效率组装树形数据

说到组装树形结构数据,一般首先想到的就是递归或者反射处理,这种处理数据的方式比较直观简单,但是有个缺点,如果数据量过大比如几万几十万,处理的速度就会非常慢。

下面是一种高效处理树形数据的代码

复制代码
@Getter
@Setter
@Accessors(chain = true)
public class Node<T extends Node<T>> implements Serializable {

    private static final long serialVersionUID = -5718813852451029714L;

    private String code;

    private String parentCode;

    private List<T> childList;

    private Integer sortNum;
}

 public static <T extends Node<T>> List<T> buildTree(List<T> nodes) {
        Map<String, T> nodeMap = new HashMap<>();
        List<T> roots = new ArrayList<>();

        for (T node : nodes) {
            nodeMap.put(node.getCode(), node);
        }

        for (T node : nodes) {
            String parentCode = node.getParentCode();
            if (parentCode == null || parentCode.isEmpty()) {
                roots.add(node);
            } else {
                Node<T> parentNode = nodeMap.get(parentCode);
                if (parentNode != null) {
                    if (parentNode.getChildList() == null) {
                        parentNode.setChildList(new ArrayList<>());
                    }
                    parentNode.getChildList().add(node);
                    parentNode.getChildList().sort(Comparator.comparing(t -> t.getSortNum() != null ? t.getSortNum() : 0));
                } else {
                    roots.add(node);
                }
            }
        }

        roots.sort(Comparator.comparing(t -> t.getSortNum() != null ? t.getSortNum() : 0));
        return roots;
    }
相关推荐
小此方32 分钟前
QT从入门到精通(一)Qt新手保姆级教程:从官网安装到项目实战,四步带你彻底搞懂Qt框架
开发语言·qt
Rain的Java大神之路40 分钟前
Spring Boot 4 把自动配置拆成 47 个模块后,我的 `dependency:tree` 翻天了:一份从排查到治理的完整实战手册
java·spring boot·后端
瑶池酒剑仙2 小时前
C++重构与代码质量完全指南:从设计模式、SOLID原则到代码审查与静态分析的工程实践(所赖君子见机)
c语言·开发语言·c++·设计模式·重构·哈希算法·visual studio
xurileidian2 小时前
第 17 篇 · 边玩边学Python · for 遍历 enumerate 与 zip
java·前端·python
郝学胜-神的一滴3 小时前
Effective Python 条款45:巧用属性注解平滑升级类属性
运维·开发语言·数据库·python·网络协议·numpy
Mikko73 小时前
Redis 主从切换期间可用吗?6.2 实测哨兵切换:应用不可写 33 秒,主从连不上、数据不一致,以及设了 ACL 后哨兵不切换
java·运维·redis·后端
不积跬步无以至千里mmbb263 小时前
【软件工艺师 rust相关课程】
开发语言·后端·rust
SEO_juper3 小时前
HTTPS 混合内容检查工具:页面全站 https 了,但还有 http 资源在拖后腿
开发语言·网络协议·http·https·node.js·json·bash
不得了zz3 小时前
11-Agent 可观测与评估:Spring AI Alibaba Admin Studio 到底解决了什么
java·人工智能·后端·spring·ai编程·springaialibaba
软件技术NINI4 小时前
基于 SpringBoot 的酒店预定系统
java·spring boot·后端