org.solovyev.common.collections.tree.TreeImpl Maven / Gradle / Ivy
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 super TreeNode> filter) {
CollectionsUtils.removeIf(this.iterator(), filter);
}
@NotNull
@Override
public List extends MutableTreeNode> 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();
}
}