Composing a Java Function and Consumer

走远了吗. 提交于 2019-12-03 12:57:55

问题


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?


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/32646249/composing-a-java-function-and-consumer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!