Why we use lambda expressions in Java?

Java 8Object Oriented ProgrammingProgramming

A lambda expression can implement a functional interface by defining an anonymous function that can be passed as an argument to some method.

  • Enables functional programming: All new JVM based languages take advantage of the functional paradigm in their applications, but programmers forced to work with Object-Oriented Programming (OOPS) till lambda expressions came. Hence lambda expressions enable us to write functional code.
  • Readable and concise code: People have started using lambda expressions and reported that it can help to remove a huge number of lines from their code.
  • Easy-to-Use APIs and Libraries: An API designed using lambda expressions can be easier to use and support other API.
  • Enables support for parallel processing: A lambda expression can also enable us to write parallel processing because every processor is a multi-core processor nowadays.

Syntax

(arg1, arg2...) -> { body }
 or
(type1 arg1, type2 arg2...) -> { body }

Example

import javax.swing.*;

@FunctionalInterface
interface Action {
   void run(String s);
}
public class LambdaExpressionTest {
   public void action(Action action) {
      action.run("Welcome to TutorialsPoint");
   }
   public static void main(String[] args) {
      new LambdaExpressionTest().action((String s) -> System.out.print("*" + s + "*")); // lambda expression
   }
}

Output

*Welcome to TutorialsPoint*
raja
Published on 26-Dec-2019 16:37:47
Advertisements