Java中Python的lambda函数等价吗? [英] Equivalent for Python's lambda functions in Java?

查看:113
本文介绍了Java中Python的lambda函数等价吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

遗憾的是, Java中的lambda。然而,你几乎可以用匿名类获得相同的效果(以一种非常丑陋的方式):

  interface MyLambda {
void theFunc(); //这里我们定义函数接口

$ b $ public class Something {
static void execute(MyLambda l){
l.theFunc(); //这个类只是想使用lambda来获得某些东西
}
}

public class Test {
static void main(String [] args){
Something.execute(new MyLambda(){//这里我们创建一个匿名类
void theFunc(){//实现MyLambda
System.out.println(Hello world!);
}
});
}
}

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

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

解决方案

Unfortunately, there are no lambdas in Java. However, you can get almost the same effect (in a really ugly way) with anonymous classes:

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 :(

这篇关于Java中Python的lambda函数等价吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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