我希望在下面的例子中用方法引用替换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表达式转换为方法引用?
::
来引用方法参数。可以用"hi"::equals
替换s -> "hi".equals(s)
,但是不能用它来替换s -> s.equals("hi")
。 - Peter LawreyMethodHandle
可以重新排列参数,但结果不再是直接的方法句柄,而LambdaMetaFactory
仅支持直接方法句柄。另一方面,部分应用的函数将起作用,因为它们不会重新排列参数,并且LMF支持从左到右的参数绑定。因此对于.endsWith(".")
,其中右参数应该被绑定,机会渺茫... - HolgerString::endsWith
,再加上一种假设的方法来绑定参数"."
。相比于s -> s.endsWith(".")
,这有什么优势呢? - Holger