Basic Understanding of lambda expression in Java 8?

A lambda expression can be memorized as methods in Java, like methods lambda expression takes the inputs as Parameter and produce the processed data. Lambda expressions are available under and introduced in Java 8.

In Short, the lambda expression included in Java 8 mainly for,

– Lambda Expression is like a function introduced to include the functionality on the way and not dependent on any classes

– Shorting the plenty of repeated codes.

– Lambda Expressions can be used to implement the Functional Interfaces 

A lambda expression is a short block of code that takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

Syntax Explanation :

(arguments) -> {body}

Eg :

(int a, int b) -> { a+b );

Here int a and int b are the parameters. In the body sections, the functional actions are handled, in the above example a+b is done, likewise, we can perform any actions like a pure java function.

lambda expression syntax

Here is a simple program to demonstrate how the lambda expressions get in java 8 to represent functional interfaces.

Without Using Lambda Expression :

interface FunctionalInterface {
  public void add(int x, int y);
}
public class LambdaExpresion {

public static void main(String[] args) {

    //Using Lambda Expression to implement FunctionalInterface 
    FunctionalInterface funcInterfaceWithLambda = (int a, int b) -> {System.out.println("Invoking through Lambda Expression : " +(a+b));};
    funcInterfaceWithLambda.add(15, 75);
}
}

Output :

Invoking through Without Lambda Expression : 300

With Using Lambda Expression :

interface FunctionalInterface {
	public void add(int x, int y);
	
}
public class LambdaExpresion {

	public static void main(String[] args) {
		
		//Using Lambda Expression to implement FunctionalInterface 
		FunctionalInterface funcInterfaceWithLambda = (int a, int b) -> {System.out.println("Invoking through Lambda Expression : " +(a+b));};
		funcInterfaceWithLambda.add(15, 75);
		
	}
}

Output :

Invoking through Lambda Expression : 90

Key Points to be Noted :

– Lambda Expressions can contain 0, 1, or more arguments

– Body of Lambda Expressions can be either one or more statements, with no restrictions.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *