Node: add {get,find}ChildNamed() methods

Both methods look for a child with the given name as an immediate child of
the current node.

findChildNamed:

Will return an Optional containing the found node or empty.

getChildNames:

Is more insistent and will return the found node itself. If a node by that
name is not found, then a NodeException will be thrown.
This commit is contained in:
Paul Campbell 2016-05-24 11:03:19 +01:00
parent b18020708b
commit b278fc0f98
2 changed files with 38 additions and 0 deletions

View file

@ -127,6 +127,25 @@ public interface Node<T> {
Optional<Node<T>> walkTree(final List<T> path);
/**
/**
* Searches for a child with the name given.
*
* @param name the name of the child
*
* @return an Optional containing the child found or empty
*/
Optional<Node<T>> findChildNamed(String name);
/**
* Returns the child with the given name. If one can't be found a
* NodeException is thrown.
*
* @param name the name of the child
*
* @return the node
*/
Node<T> getChildNamed(String name);
* Returns true if the Node has a name.
*
* @return true if the node has a name

View file

@ -286,6 +286,25 @@ public class NodeItem<T> implements Node<T> {
public Node<T> createChild(final T child) {
if (child == null) {
throw new NullPointerException("child");
@Override
public Optional<Node<T>> findChildNamed(final String named) {
if (named == null) {
throw new NullPointerException("name");
}
return children.stream()
.filter((Node<T> t) -> t.getName().equals(named))
.findAny();
}
@Override
public Node<T> getChildNamed(final String named) {
final Optional<Node<T>> optional = findChildNamed(named);
if (optional.isPresent()) {
return optional.get();
}
throw new NodeException("Named child not found");
}
@Override
public boolean isNamed() {
return name != null && name.length() > 0;