问题描述
在功能上构成java Function
和 Consumer
的最佳方式是什么?
例如给出一些函数< Object,String> f
和一些消费者< String> c
然后做 f.and然后(c)
会感觉自然,但这不是接口的工作方式。
我看到的两个选项是替换 Consumer< String> c
与函数< String,Void> c
或更改消费者< String> c
到 BiConsumer< Function< Object,String>,String> c
和do
accept(函数< Object,String> f,Object o){
String thing = f.apply(o);
//对事物做些事
}
其中之一好于另一个?有没有更好的方法?
这是你正在尝试做什么?
消费者< Object> composed = o - > c.accept(f.apply(O));
如果您发现自己遇到了这个问题,您可以使用静态方法来执行此操作):
static< T,R>消费者LT; T> applyAndAccept(Function<?super T,?extends R> f,Consumer< R> c){
return t - > c.accept(f.apply(T));
}
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));
}
这篇关于撰写Java功能和消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!