等同于 Java 中 Python 的 lambda 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/929988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:24:39  来源:igfitidea点击:

Equivalent for Python's lambda functions in Java?

javapythonfunctionlambda

提问by Zifre

Can someone please tell me if there is an equivalent for Python's lambda functions in Java?

有人可以告诉我 Java 中 Python 的 lambda 函数是否有等价物?

回答by Zifre

Unfortunately, there are no lambdas in Java until Java 8 introduced Lambda Expressions. However, you can get almostthe same effect (in a really ugly way) with anonymous classes:

不幸的是,在 Java 8 引入Lambda 表达式之前,Java 中没有 lambda 。但是,您可以使用匿名类获得几乎相同的效果(以一种非常丑陋的方式):

interface MyLambda {
    void theFunc(); // here we define the interface for the function
}

public class Something {
    static void execute(MyLambda l) {
        l.theFunc(); // this class just wants to use the lambda for something
    }
}

public class Test {
    static void main(String[] args) {
        Something.execute(new MyLambda() { // here we create an anonymous class
            void theFunc() {               // implementing MyLambda
                System.out.println("Hello world!");
            }
        });
    }
}

Obviously these would have to be in separate files :(

显然,这些必须在单独的文件中:(

回答by nategood

I don't think there is an exact equivalent, however there are anonymous classes that are about as close as you can get. But still pretty different. Joel Spolsky wrote an article about how the students taught only Java are missing out on these beauties of functional style programming: Can Your Programming Language Do This?.

我不认为有一个确切的等价物,但是有一些匿名类尽可能接近。但还是很不一样。Joel Spolsky 写了一篇关于只教 Java 的学生如何错过函数式编程的这些优点的文章:你的编程语言能做到这一点吗?.

回答by Alex Martelli

One idea is based on a generic public interface Lambda<T>-- see http://www.javalobby.org/java/forums/t75427.html.

一个想法是基于一个通用的public interface Lambda<T>——参见http://www.javalobby.org/java/forums/t75427.html

回答by Sulabh Jain

Yes,

是的,

Lambda expressions are introduced in java from java8.

Lambda 表达式是从 java8 开始在 java 中引入的。

Basic syntax for lambda expressions are:

lambda 表达式的基本语法是:

(parameters)->
{
  statements;
}

Example

例子

(String s)->
{
System.out.println(s);
}

Check this link:

检查此链接:

http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html

回答by Saber Alex

With the release of Java 8, lambda-expression is now available. And the lambda function in java is actually "more powerful" than the python ones.

随着Java 8的发布,lambda 表达式现在可用。而java中的lambda函数实际上比python函数“更强大”。

In Python, lambda-expression may only have a single expression for its body, and no returnstatement is permitted. In Java, you can do something like this: (int a, int b) -> { return a * b; };and other optional things as well.

在 Python 中,lambda 表达式的主体可能只有一个表达式,并且return不允许有任何语句。在 Java 中,您可以执行以下操作:(int a, int b) -> { return a * b; };以及其他可选操作。

Java 8 also introduces another interface called the Function Interface. You might want to check that out as well.

Java 8 还引入了另一个名为Function Interface. 您可能也想检查一下。

回答by Mark Teese

As already pointed out, lambda expressions were introduced in Java 8.

如前所述,Java 8 中引入了 lambda 表达式。

If you're coming from python, C# or C++, see the excellent exampleby Adrian D. Finlay, which I personally found much easier to understand than the official documentation.

如果您来自 python、C# 或 C++,请参阅Adrian D. Finlay的优秀示例,我个人发现它比官方文档更容易理解。

Here's a quick peek based on Adrian's example, created using a jupyter notebook with the python kernel and IJava java kernel.

这是基于 Adrian 示例的快速浏览,该示例使用带有 python 内核和IJava java 内核的 jupyter notebook 创建。

Python:

Python:

# lambda functions
add = lambda x, y : x + y
multiply = lambda x, y : x * y
# normal function. In python, this is also an object.
def add_and_print_inputs(x, y):
    print("add_and_print inputs : {} {}".format(x,y))
    return x + y
print(add(3,5), multiply(3,5), add_and_print_inputs(3,5))

Output:

输出:

add_and_print inputs : 3 5
8 15 8

Java lambda functions can be multiline, whereas in python they are a single statement. However there is no advantage here. In python, regular functions are also objects. They can be added as parameters to any other function.

Java lambda 函数可以是多行的,而在 Python 中它们是单个语句。但是,这里没有任何优势。在python中,常规函数也是对象。它们可以作为参数添加到任何其他函数。

# function that takes a normal or lambda function (myfunc) as a parameter
def double_result(x,y,myfunc):
    return myfunc(x,y) * 2
double_result(3,5,add_and_print_inputs)

Output:

输出:

add_and_print inputs : 3 5
16

Java:

爪哇:

// functional interface with one method
interface MathOp{
    int binaryMathOp(int x, int y);
}
// lambda functions
MathOp add = (int x, int y) -> x + y;
MathOp multiply = (int x, int y) -> x * y;
// multiline lambda function
MathOp add_and_print_inputs = (int x, int y) -> {
    System.out.println("inputs : " + x + " " + y);
    return x + y;};// <- don't forget the semicolon
// usage
System.out.print("" +
add.binaryMathOp(3,5) + " " +
multiply.binaryMathOp(3,5) + " " + 
add_and_print_inputs.binaryMathOp(3,5))

Output:

输出:

inputs : 3 5
8 15 8

And when used as a parameter:

当用作参数时:

// function that takes a function as a parameter
int doubleResult(int x, int y, MathOp myfunc){
    return myfunc.binaryMathOp(x,y) * 2;
}
doubleResult(3,5,add_and_print_inputs)

Output:

输出:

inputs : 3 5
16

回答by user367836

Somewhat similarly to Zifre's, you could create an interface thus

有点类似于 Zifre 的,您可以创建一个界面

public interface myLambda<In, Out> {
    Out call(In i);
}

to enable you to write, say

使你能够写作,说

Function<MyObj, Boolean> func = new Function<MyObj, Boolean>() {
    public Boolean callFor(myObj obj) {
        return obj.canDoStuff();
    };

MyObj thing = getThing;

if (func.callFor(thing)) {
    doSomeStuff();
} else {
    doOtherStuff();
}

It's still a bit kludgy, yeah, but it has input/output at least.

它仍然有点笨拙,是的,但它至少有输入/输出。