将命名函数作为参数传递 [英] Passing named functions as arguments

查看:144
本文介绍了将命名函数作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆