Iterator<T> () { return new Object() { private final Set<T> traversed = new HashSet<>(); private Iterator<T> recurse(final T elem, boolean includeHead) { if (!traversed.add(elem)) { return Collections.emptyIterator(); } if (!includeHead) { return tailOf(elem); } return flat(asIterator(elem), new LazyIterator<T>() { @Override protected Iterator<? extends T> create() { return tailOf(elem); } }); } @NotNull private Iterator<T> tailOf(final T elem) { final Iterable<? extends T> tail = filter(step.fun(elem), new BooleanFunction<T>() { @Override public boolean fun(T e) { return !traversed.contains(e); } }); return flat(tail.iterator(), flat(map(tail.iterator(), new Function<T, Iterator<T>>() { @Override public Iterator<T> fun(T obj) { return recurse(obj, false); } }))); } }.recurse(item, includeHead); }