1.

What are lambda expressions in Java?

Answer»
  • A Lambda expression is a function that can be created without including it in any class. It was introduced in Java 8.
  • It is used to provide the interface implementation which has a functional interface. It does not require defining the method again for providing the implementation, it is allowed to just write the implementation code. Thus it saves plenty of coding.
  • Lambda expression is considered as a function, the .class file will not be created by the compiler.
  • They are generally used for simple callbacks or event listeners implementation, or in functional programming with the Java Streams API.
  • Lambda Expression Syntax is:
    (argument_list) -> {body}
    THREE components of Lamda expression are:
    1. argument_list: Zero or more number of arguments.
    2. -> (arrow-token): Used to link argument_list and body of lambda expression.
    3. body: CONTAINS statements and expressions for lambda expression.
  • A Java example program to ILLUSTRATE lambda expressions by implementing the user-defined functional interface is given below:
// A functional interface with a single abstract method. interface ExampleInterface{ // An abstract method void abstractPrint(int a);}class InterviewBit{ public static void main(String args[]) { /* A lambda expression to implement the above functional interface. */ ExampleInterface OB = (int a)->{System.out.println(a)}; // This calls above lambda expression and prints 20. ob.abstractPrint(20); }}

In the above example program, Example Interface is the functional interface that has a single abstract method abstractPrint(). By using lambda expression within InterviewBit class, we are implementing the functional interface by providing implementation code for the abstract method within an interface.



Discussion

No Comment Found