如何高效率组装树形数据

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

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

复制代码
@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;
    }
相关推荐
bbq粉刷匠7 分钟前
从0开始学java--day6.5
java
向上的车轮2 小时前
无需云服务的家庭相册:OpenHarmony 上的 Rust 实践
开发语言·后端·rust
Slow菜鸟2 小时前
SpringBoot集成Elasticsearch | Elasticsearch 8.x专属Java Client
java·spring boot·elasticsearch
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 82: 环形子数组的最大和
java·数据结构·算法·leetcode·决策树·线性回归·深度优先
豐儀麟阁贵3 小时前
4.5数组排序算法
java·开发语言·数据结构·算法·排序算法
Jane-6667773 小时前
C语言——栈与队列
c语言·开发语言
“抚琴”的人3 小时前
C# 取消机制(CancellationTokenSource/CancellationToken)
开发语言·c#·wpf·1024程序员节·取消机制
Halo_tjn3 小时前
Java Map集合
java·开发语言·计算机
lsx2024063 小时前
DOM 创建节点
开发语言
程序猿小蒜4 小时前
基于springboot的车辆管理系统设计与实现
java·数据库·spring boot·后端·spring·oracle