如何高效率组装树形数据

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

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

复制代码
@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;
    }
相关推荐
北凉军9 小时前
java连接达梦数据库,用户名是其他库的名称无法指定库,所有mapper查询的都是以用户名相同的库内的表
java·开发语言·数据库
程序员张39 小时前
Mybatis条件判断某属性是否等于指定字符串
java·spring boot·mybatis
wuk9989 小时前
基于C#与三菱PLC通过TCPIP实现MC协议通信示例
java·网络·c#
沛沛老爹9 小时前
Web转AI架构篇 Agent Skills vs MCP:工具箱与标准接口的本质区别
java·开发语言·前端·人工智能·架构·企业开发
码农小卡拉9 小时前
Maven与Gradle选型指南:如何匹配项目的依赖管理需求
java·gradle·maven
avi91119 小时前
Unity 天命6源码- 商业游戏说明分析
开发语言·unity·c#·游戏开发·游戏源码
黎雁·泠崖9 小时前
吃透Java操作符进阶:算术+移位操作符 全解析(Java&C区别+完整案例+避坑指南)
java·c语言·python
低频电磁之道10 小时前
编译C++的几种方式(MSVC编译器)
开发语言·c++
Zsy_05100310 小时前
【C++】类和对象(一)
开发语言·c++
Yu_iChan10 小时前
Day10 用户端订单模块
java