Friday, 29 July 2016

Java Lambda Expression Example

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
1 > Declaring the types of the parameters is optional.
2 > Using parentheses around the parameter is optional if you have only one parameter.
3 > Using curly braces is optional (unless you need multiple statements).
4 > The “return” keyword is optional if you have a single expression that returns a value.

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));
// 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.println(n));
// Providing the type of parameter is optional 
l.forEach((Integer n) -> System.out.println(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("SORTED LIST : "+list);

  // Starting Thread using lambda expression
new Thread( () -> System.out.println("In Java8, Lambda expression rocks !!") ).start();
}
}


No comments:

Post a Comment