TreeTraversal (final @NotNull Function<?, ?> identity) { return intercept("UNIQUE", new TraversalInterceptor() { @Override public @NotNull <TT> TraversalArgs<TT> intercept(@NotNull TraversalArgs<TT> args) { final Function<? super TT, ? extends Iterable<? extends TT>> tree = args.tree; final class WrappedTree implements Condition<TT>, Function<TT, Iterable<? extends TT>> { final Function<?, ?> inner = identity; java.util.HashSet<Object> visited; @Override public boolean value(TT e) { if (visited == null) visited = new java.util.HashSet<>(); //noinspection unchecked return visited.add(((Function<TT, Object>)inner).fun(e)); } @Override public Iterable<? extends TT> fun(TT t) { return JBIterable.from(tree.fun(t)).filter(this); } } if (tree instanceof WrappedTree && Comparing.equal(identity, ((WrappedTree)tree).inner)) { return args; } WrappedTree wrappedTree = new WrappedTree(); return new TraversalArgs<>(JBIterable.from(args.roots).filter(wrappedTree), wrappedTree); } }); }