Implementing a Generic Tree Conversion Utility in Java

This article explains how to design a flexible TreeNode interface and a TreeUtil class in Java that convert flat collections into hierarchical tree structures, provides multiple static methods for object and JSON tree generation, and discusses optimization techniques for large data sets.

Top Architect
Top Architect
Top Architect
Implementing a Generic Tree Conversion Utility in Java

Hierarchical data such as file system directories, organizational charts, and product categories are common in software development, and converting flat collections into tree structures is essential for display and manipulation.

The article introduces a generic TreeNode interface that defines methods for obtaining a node's unique identifier ( getId), parent identifier ( getPid), and managing child node lists ( getChildren, setChildren) using generic types T for IDs and K for child node types.

import java.util.List;
/**
 * @Author derek_smart
 * @Date 2024/6/27 9:00
 * @Description  泛型接口
 * `T`:节点标识符类型,例如 Integer。
 * `K`:子节点类型,通常也是 TreeNode<T, K>。
 */
public interface TreeNode<T,K> {
    T getPid();
    T getId();
    List<K> getChildren();
    void setChildren(List<K> list);
}

The TreeUtil class provides static methods to transform a collection of TreeNode objects into a tree. The core method toObjTree builds a map from node IDs to nodes, then links each node to its parent or adds it to the result list as a root.

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class TreeUtil {
    private TreeUtil() {}

    public static <T extends TreeNode> List<T> toObjTree(Collection<T> list) {
        List<T> result = Lists.newArrayList();
        Map<Object,T> map = list.stream().collect(Collectors.toMap(T::getId, Function.identity()));
        list.forEach(t -> {
            if (map.containsKey(t.getPid())) {
                if (map.get(t.getPid()).getChildren() == null) {
                    map.get(t.getPid()).setChildren(Lists.newArrayList());
                }
                map.get(t.getPid()).getChildren().add(t);
            } else {
                result.add(t);
            }
        });
        return result;
    }

    public static <T extends TreeNode> JSONArray toTree(Collection<T> list) {
        return toTree(list, "id", "pid", "children");
    }

    public static <T extends TreeNode> JSONArray toTree(Collection<T> list, String id, String pid, String children) {
        return listToTree(JSONArray.parseArray(JSON.toJSONString(list)), id, pid, children);
    }

    public static <PlainArea> JSONArray toTreeArea(Collection<PlainArea> list) {
        return listToTree(JSONArray.parseArray(JSON.toJSONString(list)), "id", "parentId", "children");
    }

    /**
     * listToTree
     * 将 JSONArray 转为树状结构
     */
    public static JSONArray listToTree(JSONArray arr, String id, String pid, String child) {
        JSONArray r = new JSONArray();
        JSONObject hash = new JSONObject();
        for (int i = 0; i < arr.size(); i++) {
            JSONObject json = (JSONObject) arr.get(i);
            hash.put(json.getString(id), json);
        }
        for (int j = 0; j < arr.size(); j++) {
            JSONObject aVal = (JSONObject) arr.get(j);
            JSONObject hashVP = (JSONObject) hash.get(aVal.get(pid).toString());
            if (hashVP != null) {
                if (hashVP.get(child) != null) {
                    JSONArray ch = (JSONArray) hashVP.get(child);
                    ch.add(aVal);
                    hashVP.put(child, ch);
                } else {
                    JSONArray ch = new JSONArray();
                    ch.add(aVal);
                    hashVP.put(child, ch);
                }
            } else {
                r.add(aVal);
            }
        }
        return r;
    }
}

The utility also offers JSON‑oriented methods ( toTree) that work directly with JSONArray, facilitating integration with RESTful APIs and other JSON data sources.

An optimized version pre‑initializes child lists for all nodes and avoids repeated containsKey checks, improving performance for large collections.

// Optimized version
public static <T extends TreeNode> List<T> toObjTree(Collection<T> list) {
    if (list == null || list.isEmpty()) {
        return new ArrayList<>();
    }
    Map<Object, T> map = new HashMap<>();
    for (T node : list) {
        map.put(node.getId(), node);
        node.setChildren(new ArrayList<>()); // pre‑initialize
    }
    List<T> result = new ArrayList<>();
    for (T node : list) {
        T parent = map.get(node.getPid());
        if (parent != null) {
            parent.getChildren().add(node);
        } else {
            result.add(node);
        }
    }
    return result;
}

Overall, the TreeUtil class and TreeNode interface provide an efficient, extensible solution for handling hierarchical data in Java applications, suitable for scenarios such as organizational charts, product category trees, and other tree‑structured datasets.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaData StructuresutilityTree Structuregeneric
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.