Do lambda expressions have any use other than saving lines of code?

后端 未结 9 1543
我寻月下人不归
我寻月下人不归 2020-11-29 18:23

Do lambda expressions have any use other than saving lines of code?

Are there any special features provided by lambdas which solved problems which weren\'t easy to s

9条回答
  •  悲&欢浪女
    2020-11-29 18:57

    There are many benefits of using lambdas instead of inner class following as below:

    • Make the code more compactly and expressive without introducing more language syntax semantics. you already gave an example in your question.

    • By using lambdas you are happy to programming with functional-style operations on streams of elements, such as map-reduce transformations on collections. see java.util.function & java.util.stream packages documentation.

    • There is no physical classes file generated for lambdas by compiler. Thus, it makes your delivered applications smaller. How Memory assigns to lambda?

    • The compiler will optimize lambda creation if the lambda doesn't access variables out of its scope, which means the lambda instance only create once by the JVM. for more details you can see @Holger's answer of the question Is method reference caching a good idea in Java 8? .

    • Lambdas can implements multi marker interfaces besides the functional interface, but the anonymous inner classes can't implements more interfaces, for example:

      //                 v--- create the lambda locally.
      Consumer action = (Consumer & Serializable) it -> {/*TODO*/};
      

提交回复
热议问题