What are the advantages of Lambda Expressions in Java?


A lambda expressiois an inline code that implements a functional interface without creating a concrete or anonymous class. A lambda expression is basically an anonymous method.

Advantages of Lambda Expression

  • Fewer Lines of Code − One of the most benefits of a lambda expression is to reduce the amount of code. We know that lambda expressions can be used only with a functional interface. For instance, Runnable is a functional interface, so we can easily apply lambda expressions.
  • Sequential and Parallel execution support by passing behavior as an argument in methods − By using Stream API in Java 8, the functions are passed to collection methods. Now it is the responsibility of collection for processing the elements either in a sequential or parallel manner.
  • Higher Efficiency − By using Stream API and lambda expressions, we can achieve higher efficiency (parallel execution) in case of bulk operations on collections. Also, lambda expression helps in achieving the internal iteration of collections rather than external iteration.

Syntax

(parameters) -> expression
  or
(parameters) -> { statements; }

Example

import java.util.*;

public class LambdaExpressionTest {
   public static void main(String args[]) {
      new LambdaExpressionTest().print();
   }
   public static void print() {
      List<String> list = new ArrayList<String>();
      list.add("Tutorials Point");
      list.stream().forEach((String) -> { // lambda expression
         System.out.println("The string is: " + list);
      });
   }
}

Output

The string is: [Tutorials Point]

Updated on: 10-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements