Java Tutorial

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java List Interface

Java Queue Interface

Java Map Interface

Java Set Interface

Java Data Structures

Java Collections Algorithms

Java Miscellaneous

Advanced Java

Java APIs & Frameworks

Java Useful Resources

Java - Lambda Expressions



Java Lambda Expressions

Lambda expressions were introduced in Java 8 and were touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming and simplifies development a lot. A lambda expression works on the principle of functional interface. A Functional interface is an interface with only one method to implement. A lambda expression provides an implementation of the functional interface method.

Lambda expression simplifies functional programming a lot and makes code readable without any boilerplate code. A lambda expression can infer the type of parameter used and can return a value without a return keyword. In the case of the simple one-statement method, even curly braces can be eliminated.

Lambda Expression Syntax

A lambda expression is characterized by the following syntax.

parameter -> expression body

Characteristics of Java Lambda Expression

Following are the important characteristics of a lambda expression.

  • Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter.

  • Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required.

  • Optional curly braces − No need to use curly braces in 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.

Java Lambda Expression Example

In this example, we've one functional interface MathOperation with a method operate which can accept two int parameters, perform the operation and return the result as int. Using lambda expression, we've created four different implementations of MathOperation operate method to add,subtract,multiply and divide two integers and get the relative result. Then we've another functional interface GreetingService with a method sayMessage, which we've used to print a message to the console.

package com.tutorialspoint;

public class JavaTester {

   public static void main(String args[]) {
      JavaTester tester = new JavaTester();
		
      //with type declaration
      MathOperation addition = (int a, int b) -> a + b;
		
      //with out type declaration
      MathOperation subtraction = (a, b) -> a - b;
		
      //with return statement along with curly braces
      MathOperation multiplication = (int a, int b) -> { return a * b; };
		
      //without return statement and without curly braces
      MathOperation division = (int a, int b) -> a / b;
		
      System.out.println("10 + 5 = " + tester.operate(10, 5, addition));
      System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction));
      System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication));
      System.out.println("10 / 5 = " + tester.operate(10, 5, division));
		
      //without parenthesis
      GreetingService greetService1 = message -> System.out.println("Hello " + message);
		
      //with parenthesis
      GreetingService greetService2 = (message) -> System.out.println("Hello " + message);
		
      greetService1.sayMessage("Mahesh");
      greetService2.sayMessage("Suresh");
   }
	
   interface MathOperation {
      int operation(int a, int b);
   }
	
   interface GreetingService {
      void sayMessage(String message);
   }
	
   private int operate(int a, int b, MathOperation mathOperation) {
      return mathOperation.operation(a, b);
   }
}

Output

Let us compile and run the above program, this will produce the following result −

10 + 5 = 15
10 - 5 = 5
10 x 5 = 50
10 / 5 = 2
Hello Mahesh
Hello Suresh

Following are the important points to be considered in the above example.

  • Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService.

  • Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java.

Scope of Java Lambda Expression

Using lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time.

Using Constant in Lambda Expression

In this example, we've one functional interface GreetingService with a method sayMessage, which we've used to print a message to the console. Now in Java Tester class, we've one final class field salutation having a value "Hello! ". Now in lambda expression, we can use this field being final without any error.

Example to Use Constant in Lambda Expression

public class JavaTester {

   final static String salutation = "Hello! ";
   
   public static void main(String args[]) {
      GreetingService greetService1 = message -> System.out.println(salutation + message);
      greetService1.sayMessage("Mahesh");
   }
	
   interface GreetingService {
      void sayMessage(String message);
   }
}

Output

Let us compile and run the above program, this will produce the following result −

Hello! Mahesh

Using Lambda Expression in Collections

From Java 8 onwards, almost all collections are enhanced to accept lambda expression to perform operations on them. For example, to iterate a list, filter a list, to sort a list and so on. In this example, we're showcasing how to iterate a list of string and print all the elements and how to print only even numbers in a list using lambda expressions.

Example to Use Lambda Expression in Collections

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class JavaTester {

   public static void main(String args[]) {
    
	   // prepare a list of strings
	   List<String> list = new ArrayList<>();
	   list.add("java");
	   list.add("html");
	   list.add("python");
      
	   // print the list using a lambda expression
	   // here we're passing a lambda expression to forEach 
	   // method of list object
	   list.forEach(i -> System.out.println(i));
	   
	   List<Integer> numbers = new ArrayList<>();
	   numbers.add(1);
	   numbers.add(2);
	   numbers.add(3);
	   numbers.add(4);
	   numbers.add(5);
	   numbers.add(6);
	   numbers.add(7);
	   numbers.add(8);
	   System.out.println(numbers);
	   
	   // filter the list using a lambda expression
	   // here we're passing a lambda expression to removeIf 
	   // method of list object where we can checking 
	   // if number is divisible by 2 or not	  
	   numbers.removeIf( n -> n%2 != 0);
	   System.out.println(numbers);
   }
}

Output

Let us compile and run the above program, this will produce the following result −

java
html
python
[1, 2, 3, 4, 5, 6, 7, 8]
[2, 4, 6, 8]
Advertisements