如何高效率组装树形数据

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

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

复制代码
@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;
    }
相关推荐
沐知全栈开发几秒前
PHP MySQL WHERE 子句详解
开发语言
糖纸风筝1 分钟前
Java指南:eclipse、java-activemq与测试验证
java·开发语言·学习
小坏讲微服务4 分钟前
整合Spring Cloud Alibaba与Gateway实现跨域的解决方案
java·开发语言·后端·spring cloud·云原生·gateway
q***13615 分钟前
Spring Cloud Gateway 整合Spring Security
java·后端·spring
我也有在努力19 分钟前
禁用 idea 屏幕阅读器功能 idea support screen readers
java·ide·intellij-idea
毕设源码-钟学长27 分钟前
【开题答辩全过程】以 基于springboot的在线影院系统设为例,包含答辩的问题和答案
java·spring boot·后端
码上成长30 分钟前
<script setup> 实战模式:大型组件怎么拆?
开发语言·javascript·vue.js
xiezhr32 分钟前
Java开发中那些常见的坑,你踩过几个?
java·spring boot·spring
xiezhr44 分钟前
Java开发中最那些常见的坑,你踩过几个?
java·spring·springboot·后端开发
q***07141 小时前
Spring Boot管理用户数据
java·spring boot·后端