Java中等效的Python lambda函数是什么?

23 投票
7 回答
13317 浏览
提问于 2025-04-15 11:56

有人能告诉我,Java里有没有和Python的lambda函数相似的东西吗?

7 个回答

6

一个想法是基于一个通用的 public interface Lambda<T> -- 你可以查看这个链接了解更多信息:http://www.javalobby.org/java/forums/t75427.html

9

我觉得没有完全相同的东西,不过有一种叫做匿名类的东西,跟它差不多,但还是有点不同。Joel Spolsky写了一篇文章,讲的是只学Java的学生错过了函数式编程的一些精彩之处:你的编程语言能做到这些吗?

27

很遗憾,在Java 8之前,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!");
            }
        });
    }
}

显然,这些代码必须放在不同的文件里 :(

撰写回答