Monday 18 September 2017

Lambda Expression : Replacement of Anonymous Inner Class

Lambda Expression:
·       A new feature of java8s
·       Main intension is replacement of anonymous inner class.
·       Lambda expression is nothing but an anonymous method(method without name)

The general form is :
(para-list)->
{
   //method body

};

Let's see an example for better clarity using normal interface approach, then using anonymous inner class approach, then lambda expression approach:

Approach-1:
package java8s;

interface Transaction
{
   public void withDraw(int amt);
}

class A implements Transaction
{
   public void withDraw(int amt)
   {
       System.out.println("amount withdrawn is"+amt);
   }
}
public class LambdaExpressionExample {

   public static void main(String[] args) {
      
       A ob1=new A();  
      
       ob1.withDraw(15000);
      
   }

}

Approach-2:
package java8s;

interface Transaction
{
   public void withDraw(int amt);
}



public class LambdaExpressionExample {

   public static void main(String[] args) {
      
       Transaction ob1=new Transaction()   //Anonymous Inner Class
       {
          public void withDraw(int amt)
          {
              System.out.println("amount withdrawn is"+amt);
          }
       };
      
       ob1.withDraw(15000);
      
   }

}

Approach-3:
package java8s;

interface Transaction
{
   public void withDraw(int amt);
}
public class LambdaExpressionExample {

   public static void main(String[] args) {
       Transaction ob1=(int amt)->
          {
              System.out.println("amount withdrawn is"+amt);
          };
ob1.withDraw(1500);
       

   }

}

Output:
amount withdrawn is1500

Sorting Collections with Java Lambdas

In Java, the Comparator class is used for sorting collections. In the following examples, we will sort a list of players based on name, surname, name length and last name letter. We will first sort them as we did before, using anonymous inner classes, and then reduce our code using lambda expressions.
In the first example, we will sort our list by name. Using the old way, this looks like this:

String[] players = {"Avijit", "Chintu", "Akshay", "Santosh", "Ritesh", "Avisek", "Krushna", "Surya", "Rudra", "Biswajit"};
 
// Sort players by name using anonymous innerclass
Arrays.sort(players, new Comparator<String>() {
       @Override
       public int compare(String s1, String s2) {
              return (s1.compareTo(s2));
       }
});
 
With lambdas, the same thing can be achieved like this:
// Sort players by name using lambda expression
Comparator<String> sortByName = (String s1, String s2) -> (s1.compareTo(s2));
 
Arrays.sort(players, sortByName);
// or this
Arrays.sort(players, (String s1, String s2) -> (s1.compareTo(s2)));