Lambda Expressions in Java 8

Java 8 has introduced a new feature called Lambda expressions.It is considered to be a major change in java. As this change will bring functional programming into java. Other languages such as Scala already have this feature so this is not new to programming world, it is new to java.

Before understanding Lambda expressions, Lets first understand Functional Interface.

What is Functional Interface?

Functional interfaces are those interfaces which have only one abstract method in it. It can have more than one default or static method and can override method from java.lang.object. Lets create a functional interface:
@FunctionalInterface
public interface Decorable {

 // one abstract method
 void decorateWithCurtains();
 
 // default method
 default void decorateWithPaints()
 {
  System.out.println("Decorating using paints");
 }

 // Overriding method of java.lang.Object
 @Override
 public int hashCode();

} 

Java can itself identify Functional Interface but you can also denote interface as Functional Interface by annotating it with @FunctionalInterface.

Some popular Functional Interfaces are:
  • java.lang.Runnable
  • java.util.concurrent.Callable
  • java.awt.event.ActionListener
  • java.util.Comparator

Why Lambda Expressions?

Lets understand with help of  Anonymous Comparator:
         Country indiaCountry=new Country(1, "India");
         Country chinaCountry=new Country(4, "China");
         Country nepalCountry=new Country(3, "Nepal");
         Country bhutanCountry=new Country(2, "Bhutan");
        
         List<Country> listOfCountries = new ArrayList<Country>();
         listOfCountries.add(indiaCountry);
         listOfCountries.add(chinaCountry);
         listOfCountries.add(nepalCountry);
         listOfCountries.add(bhutanCountry); 

         //Sort by countryName

            Collections.sort(listOfCountries,new Comparator<Country>() {

                @Override
                public int compare(Country o1, Country o2) {

                    return o1.getCountryName().compareTo(o2.getCountryName());
                }
            });

The problem with Anonymous Comparator is of syntax. Each time you want to sort list using comparator, you have to remember bulky syntax.
So generally main problem with Anonymous classes are syntax.For very simple operation, we need to write complex code. To solve this problem, JDK has introduce new feature called Lambda Expressions.I will take this example after explaining lambda expression to understand , how lambda expression will reduce this complex code.

What is Lambda Expressions:

lambda expression represents an anonymous function. It comprises of a set of parameters, a lambda operator (->) and a function body .You can call it function without name,

Connection between Lambda Expression and Functional Interface:
You might be thinking I have introduced functional Interface above but how it is connected to Lambda.So Lambda expression can be applied for abstract method of functional Interface which is being implemented or being instantiated anonymously.

Structure of Lambda Expressions

(Argument List) ->{expression;} or
(Argument List) ->{statements;}  

So we can divide structure of Lambda expression to three parts:
  1.  Argument list or parameters
    • Lambda expression can have zero or more arguments.
      ()->{System.out.println("Hello")}; //Without argument, will print hello 
      (int a)->{System.out.println(a)} //; One argument, will print value of a
      (int a,int b)-> {a+b};//two argument, will return sum of these two integers
      
      
    • You can choose to not declare type of arguments as it can be inferred from context.
    • (a,b)->{a+b};//two argument, will return sum of these two numbers
    • you can not declare one argument's type and do not declare type for other argument. 
    • (int a,b)->{a+b};//Compilation error 
    • When there is a single parameter, if its type is inferred, it is not mandatory to use parentheses
      a->{System.out.println(a)}; // Will print value of number a 
  2. Array token (->)
  3. Body
    • Body can have expression or statements.
    • If there is only one statement in body,curly brace is not needed and return type of the anonymous function is same as of  body expression
    • If there are more than one statements, then it should be in curly braces and return type of anonymous function is same as value return from code block, void if nothing is returned.
Lets take some examples ,  you want to initialize thread and now you will realize, how can lambda expression can make your coding easy :
public class ThreadSample {

 public static void main(String[] args) {
  
  // old way
  new Thread(new Runnable() {
   
   @Override
   public void run() {
    System.out.println("Thread is started");
   }
  }).start();

  // using lambda Expression
  new Thread(()->System.out.println("Thread is started")).start();
 }

}

Lets take another example of Comparator which we have seen in Anonymous Comparator in java.
Create a class called Country.java
package org.arpit.java2blog;

public class Country{
    int countryId;
    String countryName;
    
    public Country(int countryId, String countryName) {
        super();
        this.countryId = countryId;
        this.countryName = countryName;
    }

    public int getCountryId() {
        return countryId;
    }
    public void setCountryId(int countryId) {
        this.countryId = countryId;
    }
    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
} 
Create a main class called ComparatorMain.java
package org.arpit.java2blog;


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ComparatorMain {

 /**
  * @author Arpit Mandliya
  */
 public static void main(String[] args) {
  Country indiaCountry=new Country(1, "India");
  Country chinaCountry=new Country(4, "China");
  Country nepalCountry=new Country(3, "Nepal");
  Country bhutanCountry=new Country(2, "Bhutan");

  List<country> listOfCountries = new ArrayList<country>();
  listOfCountries.add(indiaCountry);
  listOfCountries.add(chinaCountry);
  listOfCountries.add(nepalCountry);
  listOfCountries.add(bhutanCountry);

  System.out.println("Before Sort by name : ");
  for (int i = 0; i < listOfCountries.size(); i++) {
   Country country=(Country) listOfCountries.get(i);
   System.out.println("Country Id: "+country.getCountryId()+"||"+"Country name: "+country.getCountryName());
  }

  //Sort by countryName
  // Anonymous Comparator
  // old way
  Collections.sort(listOfCountries,new Comparator<country>() {

   @Override
   public int compare(Country o1, Country o2) {
    return o1.getCountryName().compareTo(o2.getCountryName());
   }
  });
  
  // Using lambda expression
  Collections.sort(listOfCountries,(o1,o2)-> o1.getCountryName().compareTo(o2.getCountryName()));
  
  System.out.println("After Sort by name: ");
  for (int i = 0; i < listOfCountries.size(); i++) {
   Country country=(Country) listOfCountries.get(i);
   System.out.println("Country Id: "+country.getCountryId()+"|| "+"Country name: "+country.getCountryName());
      
   }
 }

}
As you can see here, we have used lambda expression for using Comparator. SO inspite of wrting Anonymous comparator, our expression became very easy.









So we have passed 2 arguments o1 and o2, we didn't pass type because it can inferred from context.
We have only one statement here, so no need to put it in curly braces.

Lets create HelloWorld Lambda Expression Example:

Create an Interface Called HelloWorld:
package org.arpit.java2blog;

public interface HelloWorld {
 void sayHello();
}

Create a class called HelloWorldMain
package org.arpit.java2blog;

public class HelloWorldMain {

 public static void main(String args[])
 {
                // Lambda Expression 
  HelloWorld helloWorld=()->System.out.println("Hello using Lambda Expression");
  helloWorld.sayHello();
 }
}
Run above program you will get following output:
Hello using Lambda Expression
Hope you understand Lambda expression now, in next post, we will see more examples of it.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012