撰写Java功能和消费者

撰写Java功能和消费者

本文介绍了撰写Java功能和消费者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在功能上构成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功能和消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 01:00