Is there a standard way to convert a java.util.function,Consumer into a java.util.function.Function

前端 未结 2 464
夕颜
夕颜 2021-02-12 22:28

I have a Consumer that I\'d like to convert into a Function.

I could achieve that by using

public 

        
相关标签:
2条回答
  • 2021-02-12 22:45

    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.

    0 讨论(0)
  • 2021-02-12 23:04

    A standard way doesn't exist, but this should do the trick:

    Function<T, Void> adapt(final Consumer<T> consumer) {
        return t -> {
            consumer.accept(t);
            return null;
        };
    }
    

    This is following the Adapter Pattern mentioned in the accepted answer from @rgettman.

    0 讨论(0)
提交回复
热议问题