MapMulti Recursive Tree Flatten

Flatten a nested tree depth-first with a recursive mapMulti helper that feeds each node straight downstream without building intermediate lists.

JavaData Fetching

Code

snippet
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Stream;

public class TreeFlatten {

    record Node(String name, List<Node> children) {}

    // 递归走树:先把当前节点交给下游,再继续处理子树;
    // mapMulti 不需要为每个子节点建 Stream,flatten 全程零中间集合
    static void walk(Node node, int depth, Consumer<String> out) {
        out.accept("-".repeat(depth * 2) + node.name());
        for (Node child : node.children()) {
            walk(child, depth + 1, out);
        }
    }

    public static void main(String[] args) {
        Node tree = new Node("root", List.of(
                new Node("auth", List.of(
                        new Node("login", List.of()),
                        new Node("session", List.of()))),
                new Node("billing", List.of(
                        new Node("invoice", List.of())))));

        List<String> flat = Stream.of(tree)
                .<String>mapMulti((node, downstream) -> walk(node, 0, downstream::accept))
                .toList();

        flat.forEach(System.out::println);
    }
}

Tracing the logic

All of the logic lives in the classes TreeFlatten and Node and the functions walk and main.

Repetition is confined to for (Node child : node.children()) — the rest of the file is straight-line.

What to watch for

  • No registry and no lockfile entry — dependencies are absent by design.

Using it

Entry signature: static void walk(Node node, int depth, Consumer<String> out)

main is the driver: it invokes walk before returning.

Key statements

.<String>mapMulti((node, downstream) -> walk(node, 0, downstream::accept))
.toList();
out.accept("-".repeat(depth * 2) + node.name());
walk(child, depth + 1, out);

FAQ

How do you run MapMulti Recursive Tree Flatten?
Execute it straight away — the program needs nothing beyond the runtime.