Java 8 Lambda Expression

Lambda expression is the new feature added in Java 8. Lambda expression provides clear way to represent one method interface (Functional Interface) using an expression.


Ask your questions in eHowToNow Forum

Post your technical, non-technical doubts, questions in our site. Get answer as soon as possible, meanwhile you can help others by answering, unanswered questions.
To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

Key to understanding Java’s implementation of lambda expressions are two constructs. The first is the lambda expression, itself. The second is the functional interface. Let’s begin with a simple definition of each.

What is Lambada Expression

A lambda expression is just an anonymous (that is, unnamed) method. i.e function with no name and without being bounded to identifier.

However, this method is not executed on its own. Instead, it is used to implement a method defined by a functional interface. Thus, a lambda expression results in a form of anonymous class. Lambda expressions are also commonly referred to as closures.

In simple words lambda expression provides implementation for functional interface. Same functional interface method will provides different result for different lambada expressions.

Functional Interface

A functional interface is an interface that contains one and only one abstract method. Normally, this method specifies the intended purpose of the interface. Thus, a functional interface typically represents a single action.

For example, the standard interface Runnable is a functional interface because it defines only one method: run( ). Therefore, run( ) defines the action of Runnable. Furthermore, a functional interface defines the target type of a lambda expression. Here is a key point: a lambda expression can be used only in a context in which its target type is specified. One other thing: a functional interface is sometimes referred to as a SAM type, where SAM stands for Single Abstract Method.

In this tutorial I’m going to cover about lambda expression with examples . In next tutorial I’ll cover about function interface.

Why Lambda Expression

Object Oriented programming (OOP) languages evolves around Object and instances and treated them as first member of programming language, but another important entity “function” don’t get much importance as object.

In Java function can’t be exist outside object and function itself doesn’t mean that anything without object.

In functional programming languages (like scala and JavaScript) you can define function, assign them to reference variable and pass them as method argument. We can’t achieve these things before in Java. Now we can achieve this with Java 8 lambda expression. Additionally lambda expression has following benefit

  1. Lambda expression provides implementation for functional interface
  2. Less code

Lambda Expression Syntax

parameter -> expression body

Lambda expression characteristics

Flowing are the important characteristic of lambda expression

  1. Optional Type Declaration: No need to declare the data type of parameters. Compiler can interpret the same from value.  
  2. Optional Return Statement : No need to explicitly use return keyword. Compiler automatically returns value based on functional interface definition. Curly braces are required to indicate expression return values.    
  3. Optional Parenthesis: No need to use parenthesis for single parameter. Multiple parameter need parenthesis. 
  4. Optional Curly braces:  Curly braces not required of expression body has single statement.

We can use the same syntax in different way based on number of parameters. See possible syntax below

No parameter lambda syntax

() -> expression  

//or

() -> {  

}   

One parameter lambda syntax

(param1) -> {  
  
}  

//or 

(param1) -> expression

Multiple parameter lambda syntax

(param1,param2) -> {  

}  

//or 

(param1, param2) -> expression

Lambda Expression Example

package com.ehowtonow.java8;

public class LambdaExpression {

	public static void main(String args[]) {
		LambdaExpression lambdaExpression = new LambdaExpression();
			
	      //with type declaration
	      MathUtils addition = (int a, int b) -> a + b;
			
	      //with out type declaration
	      MathUtils subtraction = (a, b) -> a - b;
			
	      //with return statement along with curly braces
	      MathUtils multiplication = (int a, int b) -> { return a * b; };
			
	      //without return statement and without curly braces
	      MathUtils division = (int a, int b) -> a / b;
			
	      System.out.println("20 + 5 = " + lambdaExpression.operate(10, 5, addition));
	      System.out.println("20 / 5 = " + lambdaExpression.operate(10, 5, division));
	      System.out.println("20 x 5 = " + lambdaExpression.operate(10, 5, multiplication));
	      System.out.println("20 - 5 = " + lambdaExpression.operate(10, 5, subtraction));
			
	      //without parenthesis
	      Java8HelloWorld greetService1 = message ->
	      System.out.println("Hello " + message);
			
	      //with parenthesis
	      Java8HelloWorld greetService2 = (message) ->
	      System.out.println("Hello " + message);
			
	      greetService1.sayHello("Annamalai");
	      greetService2.sayHello("Appu");
	   }
		
	   interface MathUtils {
	      int operation(int a, int b);
	   }
		
	   interface Java8HelloWorld {
	      void sayHello(String message);
	   }
		
	   private int operate(int a, int b, MathUtils mathUtils) {
	      return mathUtils.operation(a, b);
	   }
}

20 + 5 = 15
20 / 5 = 2
20 x 5 = 50
20 – 5 = 5
Hello Annamalai
Hello Appu

Output

Ask your questions in eHowToNow Forum

To Ask new Question : Ask Question
Check our existing discussions : Questions & Answers

Posts You may Like

  1. Java 8 Stream has already been operated upon or closed
  2. How to reverse the String using StringBuffer
  3. JAX-RS to Produce JSON using Jackson – Jersey 1.x
  4. Read XML File as List of Object using SAX Parser
  5. Java 8 Sort Map by Key
  6. How to traverse the directories using Java
  7. Convert Map to JSON using Jackson 1.x
  8. Java 7 Underscores in Numeric Literals
  9. How to validate Email Address using Java Regular Expression
  10. Java Best Practice Comments
  11. Java Mail API – Introduction
  12. How to Read file using FileInputStream
  13. Download Text file using JAX-RS RESTful Webservice
  14. How to Split the String in Java
  15. Java Data type and Identifier

Be the first to comment

Leave a Reply

Your email address will not be published.


*