方法参考与Lambda表达式 [英] method reference vs lambda expression
问题描述
我想在下面的示例中用方法引用替换lambda表达式:
I want to replace lambda expression by method reference in the below example :
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表达式转换为方法引用.
is it possible to transform any lambda expression to method reference.
推荐答案
没有办法将任何lambda表达式转换为方法引用",但是如果可以满足经常性的需求,则可以为特定的目标类型实现一个工厂:
There is no way "to transform any lambda expression to method reference", but you can implement a factory for a particular target type, if this serves recurring needs:
public static <A,B> Predicate<A> bind2nd(BiPredicate<A,B> p, B b) {
return a -> p.test(a, b);
}
有了这个,你可以写
words.stream().filter(bind2nd(String::endsWith, ".")).forEach(System.out::println);
但是实际上,没有优势.从技术上讲,lambda表达式可以完全满足您的要求,其中存在最小必要的参数转换代码,表示为lambda表达式的主体,被编译为合成方法和对该合成代码的方法引用.语法
s -> s.endsWith(".")
也已经是表达该意图的最小语法.我怀疑您会找到一个较小的结构,该结构仍与其余Java编程语言兼容.
but actually, there’s no advantage. Technically, a lambda expression does exactly what you want, there’s the minimum necessary argument transformation code, expressed as the lambda expression’s body, compiled into a synthetic method and a method reference to that synthetic code. The syntax
s -> s.endsWith(".")
also is already the smallest syntax possible to express that intent. I doubt that you can find a smaller construct that would still be compatible with the rest of the Java programming language.
这篇关于方法参考与Lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!