@SuppressWarnings("unchecked") static <T, U> Tree<U> apply( Node<T> node, Function<? super T, ? extends Iterable<? extends U>> mapper) { final Tree<U> mapped = Tree.ofAll(mapper.apply(node.getValue())); if (mapped.isEmpty()) { return Tree.empty(); } else { final List<Node<U>> children = (List<Node<U>>) (Object) node.getChildren() .map(child -> FlatMap.apply(child, mapper)) .filter(Tree::isDefined); return Tree.of(mapped.getValue(), children.prependAll(mapped.getChildren())); } }
@Override default <U> Tree<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return isEmpty() ? Empty.instance() : FlatMap.apply((Node<T>) this, mapper); }