DEV Community

loading...

Lambda expressions in Java

Ravi Yasas
Software Engineer by profession. Author of https://javafoundation.xyz
・2 min read

What is a lambda expression?

  • Lambda expression is a function without any signature.
  • It doesn't have a name, return type, and modifiers.
  • It can have any number of arguments.
  • For one argument lambda expressions, parenthesis are optional.
  • Compiler can understand the data type.
  • Curly braces are mandatory for many arguments.

Advantages of Lambda expressions

  • It helps to iterate, filter, and extract data from a collection in a very efficient way.
  • It saves a lot of code.
  • Code reuse
  • Reduce class files

Functional interface

  • An interface that has only one abstract method.
  • @FunctionalInterface annotation is used to declare an interface as a functional interface.
  • Ex: Runnable interface

Lambda expression signature

  • (argument-list) -> {body}
  • Ex:
( ) -> { }        
(p1) -> { }        
(p1, p2) -> { }
Enter fullscreen mode Exit fullscreen mode

Rules

public void m1(int a, int b){    
    System.out.println(a+b);
}
    //lambda expressions
( a,b ) -> System.out.println(a+b);
Enter fullscreen mode Exit fullscreen mode
  • Lambda expression doesn't have a name, a modifier and a return type.
  • If the code contains only one line. curly braces are optional.
  • Compiler can guess the return type.
public int square(int n){
    return n*n;
}

//lambda expressions
(int n) -> {return n*n;}
(n) -> {return n*n;}
n -> n*n;
Enter fullscreen mode Exit fullscreen mode
  • If only one parameter is there, parentheses are optional.
  • Since it has only one line, curly braces are optional.
  • Without curly braces, the return type is optional.

Valid statements

Interf i = n -> n*n;
Interf i = (n) -> n*n;
Interf i = n -> {return n*n;};
Enter fullscreen mode Exit fullscreen mode

Invalid statements

Interf i = n -> return n*n;
Interf i = n -> {return n*n};
Interf i = n -> {return n*n;}
Interf i = n -> {n*n;};
Enter fullscreen mode Exit fullscreen mode

Example 01

public void m1(){
    System.out.println("Hello");
}

//lambda expressions
( ) -> System.out.println("Hello");
Enter fullscreen mode Exit fullscreen mode

Example 02

public void add(int a, int b){
    System.out.println(a+b);
}

//lambda expressions
(int a, int b) -> System.out.println(a+b);
(a, b) -> System.out.println(a+b);
Enter fullscreen mode Exit fullscreen mode

Example 03

public int square(int n){
    return n*n;
}

//lambda expressions
(int n) -> {return n*n;}
(n) -> {return n*n;}
n -> n*n;
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app