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

org.solovyev.common.collections.tree.TreeImpl Maven / Gradle / Ivy

There is a newer version: 1.0.7
Show newest version
package org.solovyev.common.collections.tree;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.solovyev.common.JPredicate;
import org.solovyev.common.collections.CollectionsUtils;
import org.solovyev.common.text.StringUtils;

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

/**
 * User: serso
 * Date: 4/1/12
 * Time: 12:22 PM
 */
public class TreeImpl implements MutableTree {

    @NotNull
    private MutableTreeNode root;

    private TreeImpl() {
    }

    @NotNull
    public static  MutableTree newInstance(@Nullable T data) {
        final TreeImpl result = new TreeImpl();

        result.root = TreeNodeImpl.newInstance(data);

        return result;
    }

    @NotNull
    @Override
    public MutableTreeNode getRoot() {
        return this.root;
    }

    @Override
    public int getSize() {
        // root + children
        int result = 1 + this.root.getOwnChildren().size();

        for (MutableTreeNode child : root.getOwnChildren()) {
            result += child.getSize();
        }

        return result;
    }

    @Override
    public void removeNodeIf(@NotNull JPredicate> filter) {
        CollectionsUtils.removeIf(this.iterator(), filter);
    }

    @NotNull
    @Override
    public List> getAllNodes() {
        final List> result = new ArrayList>();
        result.add(this.root);
        result.addAll(this.root.getAllChildren());
        return result;
    }

    @NotNull
    @Override
    public DepthTreeIterator iterator() {
        return new DepthTreeIterator(this.root);
    }

    @NotNull
    @Override
    public DepthTreeIterator getIterator() {
        return iterator();
    }

    @Override
    public String toString() {
        final StringBuilder result = new StringBuilder();

        for ( DepthTreeIterator it = iterator(); it.hasNext(); ) {
            final TreeNode node = it.next();
            result.append(StringUtils.repeat(" ", it.getDepth()));
            result.append(node.getData());
            result.append("\n");
        }

        return result.toString();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy