可以像这样链接/连接对 lambda 表达式中的元素所做的操作:
list.forEach(s -> {
System.out.println(s.toLowerCase());
System.out.println(s.toUpperCase());
});
有没有一种方法也可以通过方法引用来做到这一点?像这样:
list.forEach({
System.out::println(String::toLowerCase);
System.out::println(String::toCase);
});
我知道我可以在四个单独的调用中执行此操作(也可以执行更多操作,即改变值):
list.replaceAll(String::toLowerCase);
list.forEach(System.out::println);
list.replaceAll(String::toUpperCase);
list.forEach(System.out::println);
我什至不能做这样简单的事情:
list.forEach({
System.out::println;
System.out::println;
});
最佳答案
可以通过功能接口(interface)的默认方法进行链接。但“问题”在于,当您返回合成表达式的右侧时,推理引擎没有足够的信息来确定左侧是相同的功能接口(interface)。
要提供该信息,您必须执行以下声明:
List<String> l = Collections.emptyList();
l.forEach(((Consumer<String>)System.out::println).andThen(System.out::println));
或者先赋值给一个变量:
Consumer<String> cons = System.out::println;
Collections.<String>emptyList().forEach(cons.andThen(System.out::println));
或者,您也可以编写静态辅助方法来执行您想要的操作
Collections.<String>emptyList().forEach(combine(System.out::println, System.out::println));
static <T> Consumer<T> combine(Consumer<T>... consumers) {
// exercise left to the reader
}
关于java - 多个 lambda 方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31625299/