Java 8: Chain Consumer<Y> to Function<X,Y>

Viewed 6759

Exploring the new features of Java 8, I stumbled the wish to create a Consumer<X> by chaining a Consumer<Y> to Function<X,Y>.

Does this make sense? And if so, how would a good (general) solution look like?


What I've tried (rather a special case by example):

Given

@FunctionalInterface
public interface PartialFunction<X, Y> {
    Y apply(X x) throws Exception;
}

and

import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;

public class PartialFunctions {

    public static <X, Y> Function<X, Optional<Y>> withOptionalResults(final PartialFunction<X, Y> funcThatThrows) {
        return z -> {
            try {
                return Optional.of(funcThatThrows.apply(z));
            } catch (final Exception e) {
                return Optional.empty();
            }
        };
    }

    public static <X, Y> Consumer<X> acceptOnSuccess(final PartialFunction<X, Y> g, final Consumer<Y> c) {
        return x -> withOptionalResults(x).apply(t).ifPresent(c);
    }
}

I end up with a possible usage like:

files.forEach(PartialFunctions.<File, BufferedImage>acceptOnSuccess(
        ImageIO::read, images::add));

However, the need for the explicit generic specification is not optimal. Hopefully there is something better?

4 Answers
Related