What is the best way to functionally compose a java Function
and a Consumer
?
For example given some Function<Object, String> f
and some Consumer<String> c
then doing f.andThen(c)
would feel natural, however that is not how the interfaces work.
The two options I see are either replace Consumer<String> c
with Function<String, Void> c
or change Consumer<String> c
to BiConsumer<Function<Object, String>, String> c
and do
accept(Function<Object, String> f, Object o) {
String thing = f.apply(o);
//do something with thing
}
Is one of these better than the other? Is there a better way?
Is this what you are trying to do?
Consumer<Object> composed = o -> c.accept(f.apply(o));
If you find yourself faced with this problem a lot, you can make a static method to do this (but is it really worth it?):
static<T,R> Consumer<T> applyAndAccept(Function<? super T,? extends R> f, Consumer<R> c){
return t -> c.accept(f.apply(t));
}
You can make a copy of the java.util.function.Function interface in your own code. Call it ConsumableFunction and change all default method parameter types and return values from Function to ConsumableFunction. Then add the following default function:
default Consumer<T> atLast(Consumer<R> consumer) {
Objects.requireNonNull(consumer);
return (T t) -> consumer.accept(apply(t));
}
Now let all your Function implmementations implement ConsumableFunction instead. Then you can write code like this:
Consumer<A> consumerForA = functionFromAToB
.andThen(functionFromBToC)
.andThen(functionFromCToD)
.atLast(consumerForD);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With