Nodes.asImmutable: added to create an immutable copy of a node tree
This commit is contained in:
parent
421ad743f0
commit
f1a73366bd
1 changed files with 42 additions and 1 deletions
|
@ -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.
|
||||
*
|
||||
|
@ -52,7 +56,7 @@ public final class Nodes {
|
|||
* Creates a new named child node.
|
||||
*
|
||||
* @param data the data the node will contain
|
||||
* @param name the name of the node
|
||||
* @param name the name of the node
|
||||
* @param parent the parent of the node
|
||||
* @param <T> the type of the data
|
||||
*
|
||||
|
@ -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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue