在 java 8 中使用 lambda 表达式有什么好处?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33492203/
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-11-02 21:45:09  来源:igfitidea点击:

What are the advantages of using lambda expressions in java 8?

javalambdajava-8

提问by Prasad Revanaki

Interface AccountService{
    public void createAccount();
}

AccountService accountServiceAnonymous = new AccountService(){
    public void createAccount(){
        Account account = new Account();
        save(account);
    }
};

AccountService accountServiceLambda = () -> {
    Account account = new Account();
    save(account);
}

Apart from reduced number of lines of code, are there any other advantages of using lambda expressions in java 8 ?

除了减少代码行数之外,在 java 8 中使用 lambda 表达式还有其他优势吗?

回答by shazin

Adding to what @Bilbo has mentioned in comments. In Java 1.7 there was a new JVM Opcode was released named invokedynamicand Java 8 Lambda uses this. So the following code will result in an Anonymous class being created when you compile the code. Possible <ClassName>$1.classso if you have 10 anonymous classes that is 10 more classes in the final jar.

添加@Bilbo 在评论中提到的内容。在 Java 1.7 中发布了一个新的 JVM 操作码,命名为invokedynamicJava 8 Lambda 使用它。因此,以下代码将导致在编译代码时创建 Anonymous 类。<ClassName>$1.class如果您有 10 个匿名类,最终 jar 中还有 10 个类,则可能如此。

AccountService accountServiceAnonymous = new AccountService(){
    public void createAccount(){
        Account account = new Account();
        save(account);
    }
};

But Java 8 lambda uses invokedynamicto call lambdas thus if you have 10 lambdas it will not result in any anonymous classes thus reducing the final jar size.

但是 Java 8 lambda 用于invokedynamic调用 lambda,因此如果您有 10 个 lambda,它不会产生任何匿名类,从而减少最终 jar 的大小。

AccountService accountServiceLambda = () -> {
    Account account = new Account();
    save(account);
}

回答by ttarczynski

Another advantage of lambdas (and method references) is visible when you combine them with Stream API and other features added in Java 8, e.g. Optional.

当您将 lambda 表达式(和方法引用)与 Stream API 和 Java 8 中添加的其他功能(例如 Optional)结合使用时,它们的另一个优点是可见的。

Consider this code:

考虑这个代码:

private void pushToFront(AbstractInfo contactInfo) {
        registeredWindows.stream()
            .filter(window -> window.getWindowId() == contactInfo.getId())
            .findAny()
            .ifPresent(Window::pushToFront);
    }

The method filters the list of registered windows matching windowId with contact's id returning an Optional. If the list contains window with matching id, then the value in Optional is present and pushToFront method is then on it. Compare this to the same functionality but written in Java 7:

该方法过滤与 windowId 匹配的注册窗口列表,并返回一个 Optional 联系人的 id。如果列表包含具有匹配 id 的窗口,则 Optional 中的值存在,然后 pushToFront 方法在其上。将此与用 Java 7 编写的相同功能进行比较:

private void pushToFront(AbstractInfo contactInfo) {
    for (Window window : registeredWindows) {
        if (window.getWindowId() == contactInfo.getId() {
            window.pushToFront();
        }
    }
}

The code with lambda expression, stream and method reference, at least to me, is more concise and readable (when you get use to using streams). The example above is quite simple - but consider one, which in Java 7 would require nested loops, multiple conditional statements etc. Not easy to read even harder not to loose track of what's going on.

至少对我而言,带有 lambda 表达式、流和方法引用的代码更加简洁和可读(当您习惯使用流时)。上面的例子很简单 - 但考虑一个,在 Java 7 中需要嵌套循环、多个条件语句等。不容易阅读,更难的是不忘记正在发生的事情。

Lambdas then allow one to fully utilize other neat features of the Java 8 which among others result in neat, clean, efficient and easy to understand code.

然后,Lambda 允许人们充分利用 Java 8 的其他简洁特性,这些特性导致整洁、干净、高效且易于理解的代码。

Bottom line is, you should consider lambda expressions as part of a larger whole which are great for themselves but even better when combined with other 'building blocks' of Java 8.

最重要的是,您应该将 lambda 表达式视为更大整体的一部分,这对它们自身来说非常有用,但与 Java 8 的其他“构建块”结合使用时效果会更好。

回答by Ashutosh A

One more - unlike anonymous classes, lambdas do NOT create a new scope, they share the same scope as the enclosing block/environment.

还有一点 - 与匿名类不同,lambda 不会创建新的作用域,它们与封闭的块/环境共享相同的作用域。

So:

所以:

  1. It's easier to access the enclosing object - plain thisreference refers to the instance of the enclosing class (and you don't need to say EnclosingClass.this)

  2. There are no shadowingissues (as you cannot define local variables with the same names as variables in the enclosing scope)

  1. 访问封闭对象更容易——普通this引用是指封闭类的实例(你不需要说EnclosingClass.this

  2. 没有阴影问题(因为您不能定义与封闭范围内的变量同名的局部变量)

回答by Anand Sinha

Advantages of lambda expressions

lambda 表达式的优点

  1. It reduces the lines of code.
  2. It supports sequential and parallel execution by passing behavior in methods with collection stream API.
  3. Using Stream API and lambda expression we can achieve higher efficiency (parallel execution) in the case of bulk operations on collections.
  1. 它减少了代码行数。
  2. 它通过使用集合流 API 在方法中传递行为来支持顺序和并行执行。
  3. 使用 Stream API 和 lambda 表达式,我们可以在对集合进行批量操作的情况下实现更高的效率(并行执行)。

回答by Enrique Molinari

In addition to what has been said here, and to strictly answer the question raised, it is important to see lambdas as a "block of code" that, among other things, can be passed as parameter. That provides a huge advantage due to you can remove duplicated code.

除了这里所说的,为了严格回答提出的问题,重要的是将 lambdas 视为“代码块”,除其他外,它可以作为参数传递。这提供了巨大的优势,因为您可以删除重复的代码

How is that ? In the example above presented by @Kitke, the pushToFront(...) method, if the requirement exists, might be refactored a bit as a template and be used to filter registeredWindows by any condition. The lambda expression window -> window.getWindowId() == contactInfo.getId(), can be passed as parameter in that case. Without this powerful feature, you have to write the whileloop every time you need to filter the registeredWindowscollection by a different condition. Huge gain, re-think your code with this in mind.

那个怎么样 ?在@Kitke 提供的上述示例中,pushToFront(...) 方法(如果存在需求)可能会被重构为模板,并用于通过任何条件过滤注册的Windows。在这种情况下,可以将lambda 表达式window -> window.getWindowId() == contactInfo.getId()作为参数传递。如果没有这个强大的功能,每次需要通过不同的条件过滤注册的Windows集合时,都必须编写while循环。巨大的收获,考虑到这一点,重新思考你的代码。

Extracted from: http://www.copypasteisforword.com/notes/lambda-expressions-in-java. There you can find another example of lambda usage to remove duplicated code.

摘自:http: //www.copypasteisforword.com/notes/lambda-expressions-in-java。在那里您可以找到另一个使用 lambda 来删除重复代码的示例。