Thursday, May 30, 2013

Lambda Expression in Java 8

Current New topic in Java 8 is lambda expressions.Lambda expressions are just like  methods, a body and return type and it has arguments. It is just like anonymous methods or we can say that method without name.

There are fallowing statement about Lembda Expressions:--

1) Lambda expression does't necessory to have parameters.
2) If there are no parameters to be passed, then an empty parentheses is given.
3) Type of the passed parameter can be explicitly declared or can be taken from context.
4) Lambda expression body does't necessory to have statements.
5) Body of expression should be enclosed in curly braces, if there is only one statement curly brace is not needed.
6) Lambda expression is converted into an instance of a functional interface.

There is fallowing example for lemda expression:----

 If we have fallowing list that we want to sort it. We can do it by fallowing way.

List<Person> personList = new ArrayList<>();
personList.add(new Person("Virat", "Kohli"));
personList.add(new Person("Arun", "Kumar"));
personList.add(new Person("Rajesh", "Mohan"));
personList.add(new Person("Rahul", "Dravid"));

//Sorting using Anonymous Inner class.
Collections.sort(personList, new Comparator<Person>(){
public int compare(Person p1, Person p2){
return p1.firstName.compareTo(p2.firstName);

But We Can reduce the code and more precise by using Lembda Expression as Fallowing:

Collections.sort(personList, (p1, p2) -> p1.firstName.compareTo(p2.firstName));

No comments:

Post a Comment