【发布时间】:2016-10-24 09:58:08
【问题描述】:
我想在下面的例子中用方法引用替换 lambda 表达式:
public class Example {
public static void main(String[] args) {
List<String> words = Arrays.asList("toto.", "titi.", "other");
//lambda expression in the filter (predicate)
words.stream().filter(s -> s.endsWith(".")).forEach(System.out::println);
}
}
我想写一个这样的东西:
words.stream().filter(s::endsWith(".")).forEach(System.out::println);
是否可以将任何 lambda 表达式转换为方法引用。
【问题讨论】:
-
如果参数在实例调用中,则不能使用
::。您可以将s -> "hi".equals(s)替换为"hi"::equals,但如果它是s -> s.equals("hi"),则不能 -
幕后 MethodHandle can shuffle arguments,但这并没有在 java 方法参考语法中公开,我想知道在 inling 之后它是否真的会更快。另一方面,scala 可以通过部分应用函数来做到这一点
-
@the8472:
MethodHandle可以随机播放参数,但结果不再是直接方法句柄,LambdaMetaFactory仅支持直接方法句柄。另一方面,部分应用的函数会起作用,因为它们不会打乱参数,并且 LMF 支持从左到右的参数绑定。所以对于.endsWith("."),应该绑定正确的参数,没有机会…… -
方法引用的语法是
String::endsWith,加上一些假设的方式来绑定"."参数。比s -> s.endsWith(".")有什么优势?
标签: java lambda java-8 method-reference