All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.sviperll.maven.profiledep.util.TreeBuilder Maven / Gradle / Ivy

The newest version!
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.github.sviperll.maven.profiledep.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author vir
 */
public class TreeBuilder {
    public static  TreeBuilder createInstance(T value) {
        Node root = new Node(value, null);
        return new TreeBuilder(root, root);
    }
    private final Node root;
    private Node current;
    
    private TreeBuilder(Node root, Node current) {
        this.root = root;
        this.current = current;
    }

    public void node(T value) {
        current.nodes.add(new Tree(value, Collections.>emptyList()));
    }

    public void subtree(Tree tree) {
        current.nodes.add(tree);
    }

    public void subtree(T value, List> children) {
        List> unmodifiable = new ArrayList>();
        unmodifiable.addAll(children);
        current.nodes.add(new Tree(value, Collections.unmodifiableList(unmodifiable)));
    }

    public void beginSubtree(T value) {
        current = new Node(value, current);
    }

    public void endSubtree() {
        Node node = current;
        current = node.parent;
        current.nodes.add(node.build());
    }
    
    public Tree build() {
        while (current != root)
            endSubtree();
        return root.build();
    }

    private static class Node {
        private final T value;
        private final List> nodes = new ArrayList>();
        private final Node parent;

        private Node(T value, Node parent) {
            this.value = value;
            this.parent = parent;
        }

        private Tree build() {
            List> unmodifiable = new ArrayList>();
            unmodifiable.addAll(nodes);
            return new Tree(value, Collections.unmodifiableList(unmodifiable));
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy