Fundamentals 16 min read

Comprehensive Guide to TreeUtil: Building, Traversing, Flattening, and Sorting Tree Structures in Java

This article introduces a versatile Java TreeUtil class that demonstrates how to construct hierarchical tree structures from flat lists, perform pre-order, level-order, and post-order traversals, flatten trees back to lists, and sort nodes using generic functional interfaces, with detailed code examples.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Comprehensive Guide to TreeUtil: Building, Traversing, Flattening, and Sorting Tree Structures in Java

The article begins with an introduction to tree data structures, explaining their hierarchical nature and common use cases such as organization charts, menus, address selectors, and product categories.

It then shows how to define a tree node in Java using a

@Data public class MenuVo { private Long id; private Long pId; private String name; private Integer rank = 0; private List<MenuVo> subMenus = new ArrayList<>(); }

class, where each node holds a list of its children.

Next, the JSON representation of a tree is presented, illustrating how nested objects naturally form a tree.

The core of the article is the TreeUtil utility class. The makeTree method builds a tree from a flat list by filtering root nodes and recursively attaching children using functional interfaces:

public static <E> List<E> makeTree(List<E> list, Predicate<E> rootCheck, BiFunction<E, E, Boolean> parentCheck, BiConsumer<E, List<E>> setSubChildren) { return list.stream().filter(rootCheck).peek(x -> setSubChildren.accept(x, makeChildren(x, list, parentCheck, setSubChildren))).collect(Collectors.toList()); }

Helper methods makeChildren and overloaded versions without generics are also provided to illustrate the step‑by‑step construction of the tree.

Usage examples demonstrate building a menu tree, a department tree, and how to invoke the utility with lambda expressions.

Traversal utilities are included: forPreOrder (pre‑order), forLevelOrder (breadth‑first), and forPostOrder (post‑order). Each method accepts the tree, a Consumer to process each node, and a Function to retrieve child lists.

public static <E> void forPreOrder(List<E> tree, Consumer<E> consumer, Function<E, List<E>> getSubChildren) { for (E l : tree) { consumer.accept(l); List<E> es = getSubChildren.apply(l); if (es != null && es.size() > 0) { forPreOrder(es, consumer, getSubChildren); } } }

A flat method is provided to flatten a tree back into a list while clearing child references:

public static <E> List<E> flat(List<E> tree, Function<E, List<E>> getSubChildren, Consumer<E> setSubChildren) { List<E> res = new ArrayList<>(); forPostOrder(tree, item -> { setSubChildren.accept(item); res.add(item); }, getSubChildren); return res; }

The article also introduces a sort method that recursively sorts all nodes according to a supplied Comparator:

public static <E> List<E> sort(List<E> tree, Comparator<? super E> comparator, Function<E, List<E>> getChildren) { for (E item : tree) { List<E> childList = getChildren.apply(item); if (childList != null && !childList.isEmpty()) { sort(childList, comparator, getChildren); } } tree.sort(comparator); return tree; }

Finally, the article concludes by praising the elegance and reusability of the TreeUtil class, encouraging developers to adopt it for any hierarchical data processing task.

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.

JavaalgorithmDataStructureutilitytree
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

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.