如何高效率组装树形数据

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

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

复制代码
@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;
    }
相关推荐
BD_Marathon6 分钟前
【JavaWeb】Tomcat_WebAPP的标准结构
java·tomcat·web app
sunshine~~~7 分钟前
ROS 2 Jazzy + Python 3.12 + Web 前端案例
开发语言·前端·python·anaconda·ros2
小雨下雨的雨11 分钟前
第8篇:Redis缓存设计与缓存问题
java·redis·缓存
s91236010113 分钟前
【rust】生成带白边的标准二维码
开发语言·后端·rust
weixin_3077791319 分钟前
Jenkins Jakarta Mail API 插件:邮件功能的核心库
运维·开发语言·架构·jenkins
郝学胜-神的一滴25 分钟前
Linux进程管理:借助信号回收进程
linux·服务器·开发语言·c++·程序人生
WYiQIU26 分钟前
突破字节前端2-1⾯试: JS异步编程问题应答范式及进阶(视频教学及完整源码笔记)
开发语言·前端·javascript·vue.js·笔记·面试·github
quikai198126 分钟前
python练习第四组
开发语言·前端·python
爱上妖精的尾巴29 分钟前
5-40 WPS JS宏 综合实例应用-5(求字符串中的最大值记录)
开发语言·前端·javascript·wps·js宏·jsa
TT哇29 分钟前
【@NotBlank】@NotBlank与@NotEmpty与@NotNull区别
java·开发语言