Are lambda expressions objects in Java?


Yes, any lambda expression is an object in Java. It is an instance of a functional interface. We have assigned a lambda expression to any variable and pass it like any other object.

Syntax

(parameters) -> expression
             or
(parameters) -> { statements; }

In the below example, how a lambda expression has assigned to a variable and how it can be invoked.

Example

@FunctionalInterface
interface ComparatorTask {
   public boolean compare(int t1, int t2);
}
public class LambdaObjectTest {
   public static void main(String[] args) {
      ComparatorTask ctask = (int t1, int t2) -> {return t1 > t2;}; // lambda expression
      boolean b = ctask.compare(10, 3);
      System.out.println("The result is: " + b);
   }
}

Output

The result is: true
raja
Published on 06-Dec-2019 12:45:29
Advertisements