如何高效率组装树形数据

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

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

复制代码
@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;
    }
相关推荐
希望201743 分钟前
Golang Panic & Throw & Map/Channel 并发笔记
开发语言·golang
朗迹 - 张伟44 分钟前
Golang安装笔记
开发语言·笔记·golang
yzx99101344 分钟前
生活在数字世界:一份人人都能看懂的网络安全生存指南
运维·开发语言·网络·人工智能·自动化
小周同学@1 小时前
谈谈对this的理解
开发语言·前端·javascript
橙*^O^*安2 小时前
Go 语言基础:变量与常量
运维·开发语言·后端·golang·kubernetes
NiKo_W2 小时前
Linux 文件系统与基础指令
linux·开发语言·指令
BillKu2 小时前
推荐 Eclipse Temurin 的 OpenJDK
java·ide·eclipse
Morri32 小时前
[Java恶补day53] 45. 跳跃游戏Ⅱ
java·算法·leetcode
悟能不能悟2 小时前
eclipse怎么把项目设为web
java·eclipse
工程师小星星2 小时前
Golang语言的文件组织方式
开发语言·后端·golang