Nodes.asImmutable: added to create an immutable copy of a node tree

This commit is contained in:
Paul Campbell 2016-08-21 19:09:47 +01:00
parent 421ad743f0
commit f1a73366bd

View file

@ -1,5 +1,9 @@
package net.kemitix.node;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Utility class for {@link Node} items.
*
@ -63,4 +67,41 @@ public final class Nodes {
return new NodeItem<>(data, name, parent);
}
/**
* Creates an immutable copy of an existing node tree.
*
* @param root the root node of the source tree
* @param <T> the type of the data
*
* @return the immutable copy of the tree
*/
public static <T> Node<T> asImmutable(final Node<T> root) {
if (root.getParent().isPresent()) {
throw new IllegalArgumentException("source must be the root node");
}
final Set<Node<T>> children = getImmutableChildren(root);
return ImmutableNodeItem.newRoot(root.getData().orElse(null),
root.getName(), children);
}
private static <T> Set<Node<T>> getImmutableChildren(final Node<T> source) {
return source.getChildren()
.stream()
.map(Nodes::asImmutableChild)
.collect(Collectors.toSet());
}
private static <T> Node<T> asImmutableChild(
final Node<T> source) {
final Optional<Node<T>> sourceParent = source.getParent();
if (sourceParent.isPresent()) {
return ImmutableNodeItem.newChild(source.getData().orElse(null),
source.getName(), sourceParent.get(),
getImmutableChildren(source));
} else {
throw new IllegalArgumentException(
"source must not be the root node");
}
}
}