将命名函数作为参数传递 [英] Passing named functions as arguments
问题描述
Java 8添加了lambda表达式。以类似于匿名类的方式使用lambdas非常简单,但我想知道是否存在使用命名函数作为其他函数的参数的相关功能。例如,是否有Java方法编写以下Python代码:
Java 8 added lambda expressions. Using lambdas in a similar fashion to anonymous classes is pretty straight forward, but I'm wondering if the related functionality of using named functions as arguments to other functions exists. For example, is there a Java way to write the following Python code:
list1 = (1,2,3)
list2 = (4,5,6)
def add(a, b):
return a+b
for e in map(add, list1, list2):
print(e)
输出
5
7
9
推荐答案
是的,你可以使用像 Integer :: sum
这样的方法引用,其中允许使用lambdas。
Yes, you can use method references like Integer::sum
where lambdas are allowed.
int six = IntStream.of(1, 2, 3)
.reduce(0, Integer::sum);
这相当于
int six = IntStream.of(1, 2, 3)
.reduce(0, (a, b) -> Integer.sum(a, b));
Integer.sum
和 Double.max <在Java 8中添加了/ code>
,因此它们可以在这样的lambda中使用。
Methods like Integer.sum
and Double.max
were added in Java 8 precisely so they could be used in lambdas like this.
没有内置的方法来压缩 尽管如此,聚合多个列表就像Python一样。
There's no built-in way to "zip" together multiple lists the way Python does, though.
这篇关于将命名函数作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!