Merge pull request #25 from kemitix/stream-parents

Stream parents
This commit is contained in:
Paul Campbell 2017-02-18 19:31:45 +00:00 committed by GitHub
commit fa87142efd
4 changed files with 40 additions and 7 deletions

View file

@ -249,5 +249,12 @@ public interface Node<T> {
*
* @return a stream of all the nodes in the tree below this node
*/
Stream<Node<T>> streamAll();
Stream<Node<T>> stream();
/**
* Returns a stream of all the node's ancestor nodes.
*
* @return a stream of the node's parents recursively until the root node
*/
Stream<Node<T>> parentStream();
}

View file

@ -371,8 +371,14 @@ class NodeItem<T> implements Node<T> {
}
@Override
public Stream<Node<T>> streamAll() {
public Stream<Node<T>> stream() {
return Stream.concat(Stream.of(this), getChildren().stream()
.flatMap(Node::streamAll));
.flatMap(Node::stream));
}
@Override
public Stream<Node<T>> parentStream() {
return findParent().map(node -> Stream.concat(Stream.of(node), node.parentStream()))
.orElseGet(Stream::empty);
}
}

View file

@ -437,14 +437,14 @@ public class ImmutableNodeItemTest {
Nodes.namedChild("eight", "eight", n6);
val immutableRoot = Nodes.asImmutable(node);
//when
val result = immutableRoot.streamAll()
val result = immutableRoot.stream()
.collect(Collectors.toList());
//then
assertThat(result).as("full tree")
.hasSize(9);
// and
assertThat(immutableRoot.getChild("one")
.streamAll()
.stream()
.collect(Collectors.toList())).as("sub-tree")
.hasSize(4);
}

View file

@ -920,13 +920,13 @@ public class NodeItemTest {
val n7 = Nodes.namedChild("seven", "seven", n5);
val n8 = Nodes.namedChild("eight", "eight", n6);
//when
val result = node.streamAll()
val result = node.stream()
.collect(Collectors.toList());
//then
assertThat(result).as("full tree")
.contains(node, n1, n2, n3, n4, n5, n6, n7, n8);
// and
assertThat(n1.streamAll()
assertThat(n1.stream()
.collect(Collectors.toList())).as("sub-tree")
.containsExactlyInAnyOrder(n1, n3, n5, n7);
}
@ -945,4 +945,24 @@ public class NodeItemTest {
assertThat(Nodes.unnamedChild(null, root)
.isRoot()).isFalse();
}
@Test
public void parentStream() {
//given
val root = Nodes.namedRoot("root data", "root");
val child1 = Nodes.namedChild("child 1 data", "child 1", root);
val child2 = Nodes.namedChild("child 2 data", "child 2", root);
val child3 = Nodes.namedChild("child 3 data", "child 3", child2);
//when
val resultRoot = root.parentStream()
.collect(Collectors.toSet());
val resultChild1 = child1.parentStream()
.collect(Collectors.toSet());
val resultChild3 = child3.parentStream()
.collect(Collectors.toSet());
//then
assertThat(resultRoot).isEmpty();
assertThat(resultChild1).containsExactlyInAnyOrder(root);
assertThat(resultChild3).containsExactlyInAnyOrder(child2, root);
}
}