Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a standard way to convert a java.util.function,Consumer<T> into a java.util.function.Function<T, Void>

Tags:

java

java-8

I have a Consumer<T> that I'd like to convert into a Function<T, Void>.

I could achieve that by using

public <T> Function<T, Void> consumerToFunction(Consumer<T> consumer)
{
    return x -> {
        consumer.accept(x);
        return null;
    };
}

But I suspect that something like that might already exist in the JDK or perhaps in a common library.

like image 588
GuiSim Avatar asked Apr 16 '15 20:04

GuiSim


1 Answers

It looks like you need to adapt a Consumer<T> to a Function<T, R>. You have created a good example of the Adapter Pattern.

[T]he adapter pattern is a software design pattern that allows the interface of an existing class to be used from another interface.

You are letting a Consumer be used from a Function.

I know of no JDK built-in converter between functional interfaces, but this appears to be a good way of applying a standard pattern to solve your problem.

like image 89
rgettman Avatar answered Sep 29 '22 10:09

rgettman