Thursday, 29 December 2016

What is Lambda Expression In Java ?


Lambda Expression

The biggest new feature of java-8 is Lambda Expression. It simplifies the development a lot means it cut lines of code. The syntax for it is “parameters -> body” , Some important rules to syntax is : 
  • Declaring the types of the parameters is optional.
  • Using parentheses around the parameter is optional if you have only one parameter.
  • Using curly braces is optional (unless you need multiple statements).
  • The “return” keyword is optional if you have a single expression that returns a value.

Example Showing Lambda Expression:

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

interface MathOperation{
int operation(int a,int b);
}
public class LambdaExample {

public static void main(String[] args) {
// with variable type declaration
MathOperation add = (int a,int b) -> a+b;
System.out.println("ADDITION\t:"+add.operation(5, 2));
// without variable type declaration
MathOperation sub = (a,b) -> a-b;
System.out.println("SUBSTRACTION\t:"+sub.operation(5, 3));
// with return statement along with curly braces
MathOperation div = (a,b) -> {return a/b ; };
System.out.println("DIVIDE\t\t:"+div.operation(10, 5));
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();
// Traversing Arraylist in one line
List<Integer> l=new ArrayList<Integer>();
for(int i=0;i<10;i++){
l.add(i);
}
l.forEach( n -> System.out.print(n));
// Providing the type of parameter is optional 
l.forEach((Integer n) -> System.out.print(n));
// Sorting Arraylist using Lambda Expression in one line
List<Integer> list = new ArrayList<>();
list.add(2);
list.add(5);
list.add(3);
Collections.sort(list , (i,j) -> i.compareTo(j));
System.out.println("\nSORTED LIST : "+list);
// Traversing Map using Lambda Expression 
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);
items.forEach((k,v)->System.out.println(k+":::"+v));
}
}

Program Output :

ADDITION :7
SUBSTRACTION :2
DIVIDE :2
In Java8, Lambda expression rocks !!
01234567890123456789
SORTED LIST : [2, 3, 5]
A:::10
B:::20
C:::30
D:::40
E:::50
F:::60


Blog Author - Pushkar Khosla,
Software Developer by Profession with 3.0 Yrs of Experience , through this blog i'am sharing my industrial Java Knowledge to entire world. For any question or query any one can comment below or mail me at pushkar.itsitm52@gmail.com.

This blog is all about to learn Core Java ,Interview Programs and Coding tricks to polish your Java Knowledge. If you like the content of this blog please share this with your friends.



No comments:

Post a Comment