在Java中用Python的lambda函数等效?

22 python java lambda function

有人可以告诉我,如果在Java中有Python的lambda函数吗?

Zif*_*fre 27

不幸的是,在Java 8引入Lambda Expressions之前,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!");
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

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


nat*_*ood 9

我不认为有一个确切的等价物,但是有一些匿名类可以尽可能接近.但仍然非常不同.乔尔·斯波尔斯基(Joel Spolsky)写了一篇文章,讲述了学生如何只教Java,他们错过了这些函数式编程的优点:你的编程语言可以做到吗?.


Ale*_*lli 6

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