From b278fc0f988725d2c09b1df5ee783a9b026748ae Mon Sep 17 00:00:00 2001 From: Paul Campbell Date: Tue, 24 May 2016 11:03:19 +0100 Subject: [PATCH] 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. --- src/main/java/net/kemitix/node/Node.java | 19 +++++++++++++++++++ src/main/java/net/kemitix/node/NodeItem.java | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/main/java/net/kemitix/node/Node.java b/src/main/java/net/kemitix/node/Node.java index 66f9910..c569773 100644 --- a/src/main/java/net/kemitix/node/Node.java +++ b/src/main/java/net/kemitix/node/Node.java @@ -127,6 +127,25 @@ public interface Node { Optional> walkTree(final List 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> 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 getChildNamed(String name); + * Returns true if the Node has a name. * * @return true if the node has a name diff --git a/src/main/java/net/kemitix/node/NodeItem.java b/src/main/java/net/kemitix/node/NodeItem.java index 6815350..fb8908b 100644 --- a/src/main/java/net/kemitix/node/NodeItem.java +++ b/src/main/java/net/kemitix/node/NodeItem.java @@ -286,6 +286,25 @@ public class NodeItem implements Node { public Node createChild(final T child) { if (child == null) { throw new NullPointerException("child"); + @Override + public Optional> findChildNamed(final String named) { + if (named == null) { + throw new NullPointerException("name"); + } + return children.stream() + .filter((Node t) -> t.getName().equals(named)) + .findAny(); + } + + @Override + public Node getChildNamed(final String named) { + final Optional> 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;