Java8中是否有一种方法可以使用方法引用作为Function对象来使用其方法,例如:
Stream.of("ciao", "hola", "hello")
.map(String::length.andThen(n -> n * 2))
Run Code Online (Sandbox Code Playgroud)
这个问题与之无关Stream,它只是作为例子使用,我想对方法参考有答案
这与这个问题有关:如何进行功能组合?
我注意到方法引用可以分配给声明为的变量Function,因此我假设它应该具有andThen或compose函数,因此我希望我们可以直接组合它们.但很显然,我们需要把它们分配给声明为可变的Function第一(或类型转换调用之前)之前,我们可以称之为andThen或compose他们.
我怀疑我可能会对这应该如何运作有一些误解.
所以我的问题:
andThen方法之前,为什么我们需要先键入或将其分配给变量?示例代码如下.
public class MyMethods{
public static Integer triple(Integer a){return 3*a;}
public static Integer quadruple(Integer a){return 4*a;}
public int operate(int num, Function<Integer, Integer> f){
return f.apply(num);
}
public static void main(String[] args){
MyMethods methods = new MyMethods();
int three = methods.operate(1, MyMethods::triple); // This is fine
// Error below
// int twelve = methods.operate(1, (MyMethods::triple).andThen(MyMethods::quadruple));
// But this one is …Run Code Online (Sandbox Code Playgroud) 假设有一个典型的Java Bean:
class MyBean {
void setA(String id) {
}
void setB(String id) {
}
List<String> getList() {
}
}
Run Code Online (Sandbox Code Playgroud)
我想在BiConsumer的帮助下创建一种更抽象的方式来调用setter:
Map<SomeEnum, BiConsumer<MyBean, String>> map = ...
map.put(SomeEnum.A, MyBean::setA);
map.put(SomeEnum.B, MyBean::setB);
map.put(SomeEnum.List, (myBean, id) -> myBean.getList().add(id));
Run Code Online (Sandbox Code Playgroud)
有没有一种方法,以取代拉姆达(myBean, id) -> myBean.getList().add(id)与链接的方法引用,类似(myBean.getList())::add或者myBean::getList::add还是其他什么东西?