Lambda Expression


Lambda Expression

Lambda expressions basically express instances of functional interfaces, lambda expressions implement the only abstract function and therefore implement functional interfaces

  • Enables us to treat functionality as a method argument, or code as data.
  • A function that can be created without belonging to any class.
  • A lambda expression can be passed around as if it was an object and executed on demand.

Functional Interface

A functional interface is an interface that contains only one abstract method. They can have only one functionality to exhibit. From Java 8 onwards, lambda expressions can be used to represent the instance of a functional interface. A functional interface can have any number of default methods. Runnable, ActionListener, Comparable are some of the examples of functional interfaces.
Before Java 8, we had to create anonymous inner class objects or implement these interfaces.

// Java program to demonstrate functional interface @FunctionalInterface
public interface MyFunctionalInterface {
public void execute();
}
The above counts as a functional interface in Java because it only contains a single method, and that method has no implementation. Normally a Java interface does not contain implementations of the methods it declares, but it can contain implementations in default methods, or in static methods. Below is another example of a Java functional interface, with implementations of some of the methods: @FunctionalInterface
public interface MyFunctionalInterface2{
public void execute();

public default void print(String text) {
System.out.println(text);
}

public static void print(String text, PrintWriter writer) throws IOException {
writer.write(text);
}
}

Lambda Expression Examples

Java program to demonstrate lambda expressions to implement a user defined functional interface.
// A sample functional interface
@FunctionalInterface
interface FuncInterface{
// An abstract function
void abstractFun(int x);
}

class Test{
public static void main(String args[]){

// lambda expression to implement above
// functional interface. This interface
// by default implements abstractFun()
FuncInterface fobj = (int x)->System.out.println(2*x);

// This calls the above lambda expression and prints 10.
fobj.abstractFun(5);
}
}