Saturday, June 28, 2014

Java 8 predicate for tee

A "tee" method did not make it into Java 8 streams, but you can make your own easily enough:

public final class Tee<T>
        implements Predicate<T> {
    private final Predicate<T> test;
    private final Consumer<T> reject;

    @Nonnull
    public static <T> Predicate<T> tee(
            @Nonnull final Predicate<T> test,
            @Nonnull final Consumer<T> reject) {
        return new Tee<>(test, reject);
    }

    private Tee(final Predicate<T> test,
            final Consumer<T> reject) {
        this.test = test;
        this.reject = reject;
    }

    @Override
    public boolean test(final T t) {
        if (test.test(t))
            return true;
        reject.accept(t);
        return false;
    }

    public static void main(final String... args) {
        asList("a", "bb", "ccc", "dddd").stream().
                filter(tee(Tee::even, err::println)).
                forEach(out::println);
    }

    private static boolean even(final String s) {
        return 0 == s.length() % 2;
    }
}