Java 8 Lambda Expression - Java Tutorial 2

Lambda expressions in Java 8 :

Lambda expressions are introduced in Java 8. There are various reasons why lambda expression was added . I will try to explain you with a simple example how the code is without lambda expression and how it can be changed using lambda expression :

In this exmaple we will have :

  1. One model class Car with one String property color

  2. One interface ICarChecker with a function called public boolean isValidColor(Car car). It will check if a car is valid or not .

  3. An adapter CarCheckerAdapter that implements ICarChecker and checks for a valid color. If color is white then it is valid.

Following are the classes we have mentioned above :

Car.java

public class Car {
    String color;

    public Car (String colorType){
        color = colorType;
    }

    public String getColor() {
        return color;
    }
}

Interface ICarChecker.java

public interface ICarChecker {
    public boolean isValidColor(Car car);
}

Adapter CarCheckerAdapter.java

public class CarCheckerAdapter implements ICarChecker{

    @Override
    public boolean isValidColor(Car car) {
        return car.getColor().equalsIgnoreCase("white");
    }

}

Main class Main.java

public class Main {

    public static void main(String[] args){
        Car audi = new Car("white");
        Car bmw = new Car("black");

        CarCheckerAdapter adapter = new CarCheckerAdapter(){
            @Override
            public boolean isValidColor(Car car) {
                return super.isValidColor(car);
            }
        };

        System.out.println("Color of Audi checker result : "+adapter.isValidColor(audi));
        System.out.println("Color of bmw checker result : "+adapter.isValidColor(bmw));

    }
}

In this example, to check if a color is valid or not , we need to create one Anonymous class CarCheckerAdapter each time. Using lambda expression, we can remove this problem.Let’s see :

What is a Lambda Expression :

The syntax of lambda expression can be defined as below :

(argument) -> {body}
  1. argument is the argument we are passing. It can be empty or non-empty. For single parameter , parenthesis are optional.

  2. body contains the statements of the lambda expression. For one statement body, curly braces are optional, also return statement is optional.

  3. The type of the arguments is optional to mention, if not mentioned compiler will identify it.

  4. Lambda expression can also be used with Functional Interface , i.e. interface with only one method declaration.

Using Lambda expression to our above example :

In our above example, we can convert our Anonymous class to lambda expression as ICarChecker is a functional interface.Our Main.java will look like :

public class Main {

    public static void main(String[] args){
        Car audi = new Car("white");
        Car bmw = new Car("black");

        ICarChecker adapter = (Car car) -> {return car.getColor().equalsIgnoreCase("white");};

        System.out.println("Color of Audi checker result : "+adapter.isValidColor(audi));
        System.out.println("Color of bmw checker result : "+adapter.isValidColor(bmw));

    }
}

Instead of creating a new Adapter class and implement the interface, we have done these using only one line.

Since we have only one argument and one expression in the body with a return statement. So, as mentioned above, this lambda expression can be simplified as below :

ICarChecker adapter = car -> car.getColor().equalsIgnoreCase("white");

All these three examples will produce the same output .

Using Lambda expression with Thread and Comparator :

In this example, we will use lambda expression for Runnable to create a thread and inside this thread we will use lambda expression again with Comparator to sort one arraylist using Collections.sort method.

We are using the same example as above . Change Main.java as below :

import java.util.ArrayList;
import java.util.Collections;

public class Main {

    public static void main(String[] args){

        //1

        Car audi = new Car("white");
        Car bmw = new Car("black");
        Car bentley = new Car("red");
        Car bugatti = new Car("blue");
        Car jaguar = new Car("green");

        //2
        ArrayList carList = new ArrayList<>();
        carList.add(audi);
        carList.add(bmw);
        carList.add(bentley);
        carList.add(bugatti);
        carList.add(jaguar);

        System.out.println("Before sorting ...");
        for (Car c : carList){
            System.out.println("Car colour : "+c.getColor());
        }

        //3
        Thread sortingThread = new Thread(()->{
            Collections.sort(carList,(car1,car2) -> car1.getColor().compareTo(car2.getColor()));

            System.out.println("After sorting...");
            for (Car c : carList){
                System.out.println("Car colour : "+c.getColor());
            }
        });
        sortingThread.start();

    }
}

Explanation :

  1. Create 5 Car models with different colors. We are going to sort these models on ascending order as its color name.

  2. Add all these models in a arraylist carList

  3. Since Runnable is a functional interface, we can use Lambda expression here . Instead of writing :

 Runnable runnable=new Runnable(){
            public void run(){
               //sorting code
            }
        };

I have wrote :

()->{ }

And inside the curly braces sorting is done.

Similarly , the method ’compare’ of ’Comparator’ takes two arguments, we are using (car1,car2) -> {} to replace it. This program will look like below without using lambda expression :

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

public class Main {

    public static void main(String[] args){
        Car audi = new Car("white");
        Car bmw = new Car("black");
        Car bentley = new Car("red");
        Car bugatti = new Car("blue");
        Car jaguar = new Car("green");

        ArrayList carList = new ArrayList<>();
        carList.add(audi);
        carList.add(bmw);
        carList.add(bentley);
        carList.add(bugatti);
        carList.add(jaguar);

        System.out.println("Before sorting ...");
        for (Car c : carList){
            System.out.println("Car colour : "+c.getColor());
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                Comparator comparator = new Comparator() {
                    @Override
                    public int compare(Car car1, Car car2) {
                        return car1.getColor().compareTo(car2.getColor());
                    }
                };

                Collections.sort(carList,comparator);

                System.out.println("After sorting...");
                for (Car c : carList){
                    System.out.println("Car colour : "+c.getColor());
                }
            }
        };

        Thread sortingThread = new Thread(runnable);
        sortingThread.start();

    }
}

Similar tutorials :