Class ListToTreeConverter

java.lang.Object
cloud.opencode.base.tree.builder.ListToTreeConverter

public final class ListToTreeConverter extends Object
List To Tree Converter 列表转树转换器

Converts flat list to tree structure.

将扁平列表转换为树结构。

Features | 主要功能:

  • Flat list to tree conversion - 扁平列表转树结构转换
  • Root ID detection (null, 0, empty) - 根ID检测(null、0、空)
  • Custom extractor support - 自定义提取器支持
  • Sorted tree output - 排序树输出

Usage Examples | 使用示例:

// Convert flat list to tree
List<MyNode> roots = ListToTreeConverter.convert(nodeList);

// With specific root ID
List<MyNode> roots = ListToTreeConverter.convert(nodeList, 0L);

// With sorting
List<MyNode> roots = ListToTreeConverter.convertSorted(
    nodeList, null, Comparator.comparing(MyNode::getName));

Security | 安全性:

  • Thread-safe: No (operates on input list) - 否(操作输入列表)
  • Null-safe: Yes (returns empty list for null input) - 是(null输入返回空列表)

Performance | 性能特性:

  • Time complexity: O(n) - single pass to build map, single pass to link parents - 时间复杂度: O(n) - 一次遍历建立映射,一次遍历关联父节点
  • Space complexity: O(n) - ID-to-node map proportional to list size - 空间复杂度: O(n) - ID到节点映射与列表大小成正比
Since:
JDK 25, opencode-base-tree V1.0.0
Author:
Leon Soo www.LeonSoo.com
See Also:
  • Method Details

    • convert

      public static <T extends Treeable<T,ID>, ID> List<T> convert(List<T> nodes)
      Convert list to tree 列表转树
      Type Parameters:
      T - the node type | 节点类型
      ID - the ID type | ID类型
      Parameters:
      nodes - the node list | 节点列表
      Returns:
      the root nodes | 根节点列表
    • convert

      public static <T extends Treeable<T,ID>, ID> List<T> convert(List<T> nodes, ID rootId)
      Convert list to tree with root ID 使用根ID将列表转树
      Type Parameters:
      T - the node type | 节点类型
      ID - the ID type | ID类型
      Parameters:
      nodes - the node list | 节点列表
      rootId - the root ID | 根ID
      Returns:
      the root nodes | 根节点列表
    • convertSorted

      public static <T extends Treeable<T,ID>, ID> List<T> convertSorted(List<T> nodes, ID rootId, Comparator<T> comparator)
      Convert list to tree with comparator 使用比较器将列表转树
      Type Parameters:
      T - the node type | 节点类型
      ID - the ID type | ID类型
      Parameters:
      nodes - the node list | 节点列表
      rootId - the root ID | 根ID
      comparator - the comparator | 比较器
      Returns:
      the sorted root nodes | 排序后的根节点列表
    • convert

      public static <T, N extends Treeable<N,ID>, ID> List<N> convert(List<T> items, Function<T,ID> idExtractor, Function<T,ID> parentIdExtractor, Function<T,N> nodeFactory)
      Convert using extractors 使用提取器转换
      Type Parameters:
      T - the item type | 项类型
      N - the node type | 节点类型
      ID - the ID type | ID类型
      Parameters:
      items - the item list | 项列表
      idExtractor - the ID extractor | ID提取器
      parentIdExtractor - the parent ID extractor | 父ID提取器
      nodeFactory - the node factory | 节点工厂
      Returns:
      the root nodes | 根节点列表