What are the characteristics of lambda expressions in Java?

Java 8Object Oriented ProgrammingProgramming

The lambda expressions were introduced in Java and facilitate functional programming. A lambda expression works nicely together only with functional interfaces and we cannot use lambda expressions with more than one abstract method.

Characteristics of Lambda Expression

  • Optional Type Declaration − There is no need to declare the type of a parameter. The compiler inferences the same from the value of the parameter.
  • Optional Parenthesis around Parameter − There is no need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.
  • Optional Curly Braces − There is no need to use curly braces in the expression body if the body contains a single statement.
  • Optional Return Keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value.

Syntax

parameter -> expression body
(int a, int b) -> {return a + b}

Example

@FunctionalInterface
interface TutorialsPoint {
   void message();
}
public class LambdaExpressionTest {
   public static void main(String args[]) {
      // Lambda Expression
      TutorialsPoint tp = () -> System.out.println("Welcome to TutorialsPoint");
      tp.message();
   }
}

Output

Welcome to TutorialsPoint
raja
Published on 11-Dec-2019 13:35:25
Advertisements