如何高效率组装树形数据

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

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

复制代码
@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;
    }
相关推荐
2301_8194143021 分钟前
C++与区块链智能合约
开发语言·c++·算法
不想看见40429 分钟前
Valid Parentheses栈和队列--力扣101算法题解笔记
开发语言·数据结构·c++
炸膛坦客32 分钟前
单片机/C/C++八股:(十五)内存对齐、结构体内存对齐
c语言·开发语言·单片机
娇娇yyyyyy41 分钟前
QT编程(13): Qt 事件机制eventfilter
开发语言·qt
bcbobo21cn1 小时前
C# byte类型和byte数组的使用
开发语言·c#·字节数组·byte类型
计算机安禾1 小时前
【C语言程序设计】第37篇:链表数据结构(一):单向链表的实现
c语言·开发语言·数据结构·c++·算法·链表·蓝桥杯
阿贵---1 小时前
C++构建缓存加速
开发语言·c++·算法
没有bug.的程序员1 小时前
Serverless 弹性扩容引发的全线熔断:Spring Boot 启动耗时从 1s 压缩至 0.3s 的物理级绞杀
java·spring boot·kubernetes·serverless·扩容·线上
紫丁香1 小时前
pytest_自动化测试3
开发语言·python·功能测试·单元测试·集成测试·pytest
bearpping1 小时前
java进阶知识点
java·开发语言