Lambda Expression
- Lambda expression is a new feature in Java 8 .
- Alternative to anonymous class implementation of interfaces ( with single abstract method ).
- syntax : (parameters) -> { body of statements }
Example – Sorting the list of Employees using comparator
Lets use the following employee class objects for adding to the list.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Employee { private String name; private int salary ; public Employee(String name, int salary ) { this.name = name; this.salary = salary; } public String getName() { return name; } public int getSalary() { return salary; } } |
Old way ( before Java 8 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ExampleWithoutLambdaExp{ public static void main(String[] args) { List list = new ArrayList() ; list.add(new Employee("Naveen",1000)); list.add(new Employee("Hari",2000)); list.add(new Employee("Raju",9000)); // sort by name using anonymous class implementation of Comparator ( interface having single method ) Collections.sort(list, new Comparator() { @Override public int compare(Employee e1, Employee e2) { return e1.getName().compareTo(e2.getName()); } }); System.out.println("Sorted by Name :"); for (Employee employee : list) { System.out.println("Name : " + employee.getName() + " , Salary : " + employe e.getSalary()); } } } |
Using Lambda expression ( available from Java 8 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class ExampleWithLambdaExp { public static void main(String[] args) { List list = new ArrayList() ; list.add(new Employee("Naveen",1000)); list.add(new Employee("Hari",2000)); list.add(new Employee("Raju",9000)); // sort by name using lambda expression.Using lambda expression for creating the object of comparator. // Compiler automatically knows that the second parameter (object formed by lambda exp) is of type Comparator with the help of sort() declaration. Collections.sort(list, (e1,e2) -> e1.getName().compareTo(e2.getName())); System.out.println("Sorted by Name :"); for (Employee employee : list) { System.out.println("Name : " + employee.getName() + " , Salary : " + employe e.getSalary()); } } } |
Output
Sorted by Name :
Name : Hari , Salary : 2000
Name : Naveen , Salary : 1000
Name : Raju , Salary : 9000
References
Java 8 – new features and enhancements with examples
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/Lambda-QuickStart/index.html
