Java 8 – Lambda Expression

What is Lambda expression in java 8?

Lambda expressions basically express instances of functional interfaces .Functional interface is an interface which has only one abstract method. Functional interfaces can have any number of default and static methods. But, they must have only one abstract method.

Ex. Comparator, Runnable interface.

Syntax:

(argumen1, argument2 ) -> { System.out.println(“Argument 1 is: “+ argument1 + “Argument 2 is: “+ argument2); };

@java.lang.FunctionalInterface
interface FunctionalInterface{
    //An abstract method
    void play(String sport);
    static void dance(){
        System.out.println("I am dancing");
    }
    default void run(){
        System.out.println("I am running");
    }

}


public class FunctionalInterfaceDemo{

    public static void main(String[] args) {

        FunctionalInterface fi = (game) -> {
            System.out.println("Lets play : "+ game);
        };

        fi.play("Badminton");
        fi.run();
        FunctionalInterface.dance();
    }
}

Output:

Lets play : Badminton
I am running
I am dancing

How does Lambda expression replace anonymous inner classes used before java 8?

Before Java 8, anonymous inner classes are used to implement functional interfaces. After Java 8, you can use lambda expressions to implement functional interfaces. Below are the functional interfaces in java –

@FunctionalInterface
public interface ActionListener extends EventListener 
{
    public void actionPerformed(ActionEvent e);  //Only One abstract method
}

@FunctionalInterface
public interface Runnable 
{
    public abstract void run();   //Only one abstract method
}

@FunctionalInterface
public interface Comparator 
{
    int compare(T o1, T o2);       //Only one abstract method
}

We used anonymous inner classes to provide the implementation for the abstract methods present in these above functional interfaces.

Example 1: Anonymous Inner class before Java 8(Comparator):

Comparator<Student> idComparator = new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return s1.getID()-s2.getID();
            }
        };

Lambda Expression in java 8:

Comparator<Student> idComparator = (Student s1, Student s2) -> s1.getID()-s2.getID();

Example 2: Anonymous Inner class before Java 8(Runnable):

Runnable r = new Runnable() {   
            @Override
            public void run() {
                System.out.println("Runnable Implementation Using Anonymous Inner Class");
            }
        };

Lambda Expression in java 8:

Runnable r = () -> System.out.println("Runnable Implementation Using Lambda Expressions");

You might have noticed that lambdas instantiate functional interfaces and implement their abstract method in a single line. Before Java 8, anonymous inner classes are used for this purpose. But, they end up writing more lines of code than actually needed. Lambdas let you to write less code for same task.

Where else can we use Lambda expressions ?

  • As we seen earlier, it can be used to implement function interaces.
  • Its also used extensively in stream API.
  • Foreach loop using Lambda expression –
public class FunctionalInterfaceDemo{

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);

        System.out.println("List using Lambda expression");
        list.forEach((n) -> System.out.println(n));

    }
}

Output:

List using Lambda expression
1
2
3
4
5

Leave a Comment

Close Bitnami banner
Bitnami