如何高效率组装树形数据

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

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

复制代码
@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;
    }
相关推荐
hanbr34 分钟前
C++ 初涉
开发语言·c++
Дерек的学习记录35 分钟前
C++:入门基础(下)
开发语言·数据结构·c++·学习·算法·visualstudio
hzc098765432140 分钟前
Spring Integration + MQTT
java·后端·spring
云小逸1 小时前
【nmap源码解析】Nmap 核心技术深度解析:从源码到实战
开发语言·网络·windows·nmap
前路不黑暗@1 小时前
Java项目:Java脚手架项目的公共模块的实现(二)
java·开发语言·spring boot·学习·spring cloud·maven·idea
人道领域1 小时前
Spring核心注解全解析
java·开发语言·spring boot
云深麋鹿2 小时前
标准库中的String类
开发语言·c++·容器
金牌归来发现妻女流落街头2 小时前
日志级别是摆设吗?
java·spring boot·日志
脱离语言3 小时前
Jeecg3.8.2 前端经验汇总
开发语言·前端·javascript
MOONICK3 小时前
C#基础入门
java·开发语言