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

com.jongsoft.lang.collection.impl.TreeSet Maven / Gradle / Ivy

package com.jongsoft.lang.collection.impl;

import com.jongsoft.lang.API;
import com.jongsoft.lang.collection.Iterator;
import com.jongsoft.lang.collection.Tree;
import com.jongsoft.lang.collection.support.Collections;
import com.jongsoft.lang.control.impl.Some;

public class TreeSet extends Some implements Tree {

    private String label;
    private Tree parent;
    private NodeCollection children;

    public TreeSet(String label, T value) {
        super(value);

        this.label = label;
        this.children = new NodeCollectionImpl<>(new Object[0]);
    }

    public TreeSet(String label, T value, Tree parent) {
        super(value);

        this.label = label;
        this.parent = parent;
        this.children = new NodeCollectionImpl<>(new Object[0]);
    }

    public TreeSet(String label, T value, Iterable> children) {
        super(value);

        this.label = label;
        this.children = new NodeCollectionImpl<>(API.Set(children)
                .iterator()
                .toNativeArray());
    }

    @Override
    public Tree parent() {
        return parent;
    }

    @Override
    public NodeCollection children() {
        return children;
    }

    @Override
    public String label() {
        return label;
    }

    @Override
    public Tree appendChild(final String label, final T child) {
        final Tree childNode = new TreeSet<>(label, child, this);

        Object[] rawChildren = Iterator.concat(this.children.iterator(), Iterator.>of(childNode))
                                       .toNativeArray();

        this.children = new NodeCollectionImpl<>(rawChildren);
        return this;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder("Tree: {value:")
                .append(get())
                .append(", label: ")
                .append(label);
        builder.append(Collections.textValueOf(", children:", children));
        builder.append("}");
        return builder.toString();
    }

    private class NodeCollectionImpl extends HashSet> implements NodeCollection {

        public NodeCollectionImpl(final Object[] delegate) {
            super(delegate);
        }

    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy