Java 8 - Lambda Expression example

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.

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 )

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 )

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());
  }
 }
}
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

 

Submit a Comment

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

www.000webhost.com