@SuppressWarnings("unchecked") @Override default Tuple2<Seq<T>, Seq<T>> span(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (isEmpty()) { return Tuple.of(Stream.empty(), Stream.empty()); } else { return (Tuple2<Seq<T>, Seq<T>>) traverse().span(predicate); } }
static <T> Stream<T> levelOrder(Tree<T> tree) { Stream<T> result = Stream.empty(); final java.util.Queue<Tree<T>> queue = new java.util.LinkedList<>(); queue.add(tree); while (!queue.isEmpty()) { final Tree<T> next = queue.remove(); result = result.prepend(next.getValue()); queue.addAll(next.getChildren().toJavaList()); } return result.reverse(); }
static <T> Stream<T> inOrder(Tree<T> tree) { if (tree.isLeaf()) { return Stream.of(tree.getValue()); } else { final List<Node<T>> children = tree.getChildren(); return children .tail() .foldLeft(Stream.<T>empty(), (acc, child) -> acc.appendAll(inOrder(child))) .prepend(tree.getValue()) .prependAll(inOrder(children.head())); } }
@Override default Seq<T> takeRight(int n) { if (isEmpty()) { return Stream.empty(); } else { return traverse().takeRight(n); } }
@Override default Seq<T> dropRight(int n) { if (n >= length()) { return Stream.empty(); } else { return traverse().dropRight(n); } }
@Override default Seq<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); if (isEmpty()) { return Stream.empty(); } else { return traverse().filter(predicate); } }
@Override default <U> Seq<T> distinctBy(Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor, "keyExtractor is null"); if (isEmpty()) { return Stream.empty(); } else { return traverse().distinctBy(keyExtractor); } }
@Override default Seq<T> distinctBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); if (isEmpty()) { return Stream.empty(); } else { return traverse().distinctBy(comparator); } }
/** * Traverses the Tree in a specific order. * * @param order the tree traversal order * @return A List containing all elements of this tree, which is List if this tree is empty. * @throws java.lang.NullPointerException if order is null */ default Seq<T> traverse(Order order) { Objects.requireNonNull(order, "order is null"); if (isEmpty()) { return Stream.empty(); } else { switch (order) { case PRE_ORDER: return Traversal.preOrder(this); case IN_ORDER: return Traversal.inOrder(this); case POST_ORDER: return Traversal.postOrder(this); case LEVEL_ORDER: return Traversal.levelOrder(this); default: throw new IllegalStateException("Unknown order: " + order.name()); } } }
static <T> Stream<T> postOrder(Tree<T> tree) { return tree.getChildren() .foldLeft(Stream.<T>empty(), (acc, child) -> acc.appendAll(postOrder(child))) .append(tree.getValue()); }
static <T> Stream<T> preOrder(Tree<T> tree) { return tree.getChildren() .foldLeft(Stream.of(tree.getValue()), (acc, child) -> acc.appendAll(preOrder(child))); }