Java 8 Lambda Expression

As java is an object oriented language and everything in java are objects, except primitive types. We need object references to call any method. But what in case of Java script. We can define functions anywhere we want, can assign functions to any variables, and can pass functions as an input parameters to a method. It is called functional programming language. Lambda expression is a way to visualize this functional programming in the java object oriented world. It enables to pass a functionality as a method argument. In java, lambda expressions are similar to functional programming, but not 100%.

Lambda expression is used to provide the implementation of functional interface. A Functional Interface is an interface with only single abstract method. In case of lambda expression, we don’t need to define the method again for providing the implementation so it saves lots of coding efforts.

Java Lambda Expression Syntax

(argument-list) -> {function-body}  

Where:
Argument-list: It can be empty or non-empty as well.
Arrow notation/lambda notation: It is used to link arguments-list and body of expression.
Function-body: It contains expressions and statements for lambda expression.

Lambda expression advantage:

  • It reduce lines of code.
  • It provides sequential and parallel execution support.
  • It provides a way to pass behaviors into methods.

Simple example without lambda expression

package com.w3schools;

@FunctionalInterface  
interface AddInterface{  
    void add(int a, int b);  
}  

public class FunctionalInterfaceExample {
	public static void main(String args[]){
		//without lambda, AddInterface implementation using anonymous class
		AddInterface addInterface=new AddInterface(){  
			public void add(int a, int b) {
			 System.out.println(a + b);				
			} 
		};
		addInterface.add(10, 20);  
	}
}

Output

30

Simple example with lambda expression

package com.w3schools;

@FunctionalInterface  
interface AddInterface{  
    void add(int a, int b);  
}  

public class LambdaExpressionExample {
	public static void main(String args[]){
		//Using lambda expressions
		AddInterface addInterface=(a, b)->{
			 System.out.println(a + b);				 
		};
		addInterface.add(10, 20);  
	}
}

Output

30

Java 8 lambda expression example list