Composing a Java Function and Consumer

扶醉桌前 提交于 2019-12-03 03:08:06

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);

Isn't this accomplished using map and forEach?

public void test() {
    Function<Object, String> f = (Object t) -> t.toString();
    Consumer<String> c = (String t) -> {
        System.out.println(t);
    };
    List<Object> data = new ArrayList<>();
    data.stream().map(f).forEach(c);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!