java - 函数式方法与类中的普通方法

标签 java java-8

当不在方法本身中使用此功能方法时,使用函数方法(闭包)普通java方法有什么区别。还有其他好处(例如更快的访问速度)吗?

版本 1:

public class Test{

    // does not need to be consumer, can also be 
    // own function (see version 3)
    public static final Consumer<User> addUser = s -> {
        // the same logic as in version 2
    };
}

版本 2:

public class Test{
    public static final void addUser(User u) {
        // the same logic as in version 1
    }
}

版本 3:

public class Test{

Function<User, String> addUser= (User e)-> {/* the same logic as in version 2 */;return "saved";};
}

最佳答案

第一次调用 Consumer 时会比较慢,因为您的 lambda 表达式将在下面旋转一个类,该类将使用您定义的逻辑实现 Consumer::accept提供,但这种情况仅在第一次调用时发生一次。

例如,您可以传递 Consumer,但不能传递方法。好吧,有些 MethodHandles 允许将指针/引用传递给方法。

关于java - 函数式方法与类中的普通方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48410442/

相关文章:

java - 不支持 Major.minor 版本 52.0 - 使用较低版本进行编译时。怎么还变坏了?

java - 使用 Java 8 的整数列表的总和

java - 使用 addlistnerForSingleValueEvent 从 firebase 检索数据时出错

java - 巨大的随机数排序列表

java - SugarCRM 关系可从活跃的机会中获取联系人

java - 在 AWS Lambda 中集成 Google Guice

java - 列表 foreach 方法

java - 处理列表流并收集到只有非空值的 map/ImmutableMap

java - 约束无效 : there is no unique or primary key constraint on table that matches the number and types of the columns in the foreign key

java - 在 Set 上运行两个循环