Java Lambda Expressions Interview Questions and Answers

In this article, we will discuss some important and frequently asked Java Lambda Expressions Interview Questions and Answers.
Learn Java 8 Lambda expressions with examples at Lambda Expressions guide.

1. What is a Lambda Expression?

Lambda expression is simply a function without having any name. It can even be used as a parameter in a function. Lambda Expression facilitates functional programming and simplifies the development a lot.

The main use of Lambda expression is to provide an implementation for functional interfaces.
Example 1: Lambda expression provides an implementation for Printable functional interface:

interface Printable {
    void print(String msg);
}

public class JLEExampleSingleParameter {

    public static void main(String[] args) {
         // without lambda expression
         Printable printable = new Printable() {
            @Override
            public void print(String msg) {
               System.out.println(msg);
            }
         };
         printable.print(" Print message to console....");
  
         // with lambda expression
         Printable withLambda = (msg) -> System.out.println(msg);
         withLambda.print(" Print message to console....");
     }
}
Output :
 Print message to console....
 Print message to console....

Example 2: Create a method that takes a lambda expression as a parameter:

interface StringFunction {
    String run(String str);
}

public class Main {
     public static void main(String[] args) {
       StringFunction exclaim = (s) -> s + "!";
       StringFunction ask = (s) -> s + "?";
       printFormatted("Hello", exclaim);
       printFormatted("Hello", ask);
    }
    public static void printFormatted(String str, StringFunction format) {
       String result = format.run(str);
       System.out.println(result);
     }
}
Example 3: Pass lambda expression as an argument to the constructor
    static Runnable runnableLambda = () -> {
        System.out.println("Runnable Task 1");
        System.out.println("Runnable Task 2");
    };
   //Pass lambda expression as argument
    new Thread(runnableLambda).start();
Read more in-detail about lambda expressions at Java 8 Lambda Expressions

2. Why use Lambda Expression?

  1. Facilitates functional programming - Lambda Expression facilitates functional programming and simplifies the development a lot.
  2. To provide the implementation of the Java 8 Functional Interface.
  3. Reduced Lines of Code - One of the clear benefits of using lambda expression is that the amount of code is reduced, we have already seen that how easily we can create instances of a functional interface using lambda expression rather than using an anonymous class.
  4. Passing Behaviors into methods - Lambda Expressions enable you to encapsulate a single unit of behavior and pass it to other code. For example, to other methods or constructors.
Read more in detail about lambda expressions at Java 8 Lambda Expressions.

3. Explain Lambda Expression Syntax

Java Lambda Expression Syntax:
(argument-list) -> {body}  
Java lambda expression consists of three components.
  • Argument-list: It can be empty or non-empty as well.
  • Arrow-token: It is used to link arguments-list and body of expression.
  • Body: It contains expressions and statements for the lambda expression.
For example, Consider we have a functional interface:
interface Addable{  
    int add(int a,int b);  
} 
Let's implement the above Addable functional interface using a lambda expression:
        Addable withLambdaD = (int a,int b) -> (a+b);  
        System.out.println(withLambdaD.add(100,200)); 
Read more in detail about lambda expressions at Java 8 Lambda Expressions.

4. Which of the following are valid lambda expressions? 

A.

String a, String b -> System.out.print(a+ b);

B.

() -> return;

C.

(int i) -> i;

D.

(int i) -> i++; return i;

Answer

The correct answer is C.

Explanation 

Option C is valid. The body doesn't need to use the return keyword if it only has one statement.

5. Write a Java Lambda Expression to Create Thread

The Runnable interface is a functional interface so we can use Lambda expression to implement Runnable functional interface.

Example:

public class JLEExampleRunnable {

    public static void main(String[] args) {
  
    //without lambda, Runnable implementation using anonymous class  
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println(" Runnable example without lambda exp.");
        }
    };
    Thread thread = new Thread(runnable);
    thread.start();
  
     //with lambda 
    Runnable withLambda = () -> System.out.println(" Runnable example with lambda exp.");
    Thread thread1 = new Thread(withLambda);
    thread1.start();
  }
}
Output :
 Runnable example without lambda exp.
 Runnable example with lambda exp.

6. How Lambda Expression and Functional Interfaces are Related?

The main use of Lambda expression is to provide an implementation for functional interfaces.

For example, Lambda expression provides an implementation for Printable functional interface:

interface Printable {
    void print(String msg);
}

public class JLEExampleSingleParameter {

    public static void main(String[] args) {
         // without lambda expression
         Printable printable = new Printable() {
            @Override
            public void print(String msg) {
               System.out.println(msg);
            }
         };
         printable.print(" Print message to console....");
  
         // with lambda expression
         Printable withLambda = (msg) -> System.out.println(msg);
         withLambda.print(" Print message to console....");
     }
}
Output :
 Print message to console....
 Print message to console....

7. Explain Various Forms of Writing Lambda Expression?

Java Lambda Expression with No Parameter:

interface Sayable {
    public String say();
}
public class JLEExampleNoParameter {
    public static void main(String[] args) {
        // without lambda expression
        Sayable sayable = new Sayable() {
            @Override
            public String say() {
                return "Return something ..";
            }
        };
        sayable.say();

        // with lambda expression
        Sayable withLambda = () -> {
            return "Return something ..";
        };
        withLambda.say();
    }
}

Java Lambda Expression with Single Parameter:

interface Printable {
    void print(String msg);
}

public class JLEExampleSingleParameter {

    public static void main(String[] args) {
     // without lambda expression
         Printable printable = new Printable() {
            @Override
            public void print(String msg) {
               System.out.println(msg);
            }
         };
         printable.print(" Print message to console....");
  
         // with lambda expression
         Printable withLambda = (msg) -> System.out.println(msg);
         withLambda.print(" Print message to console....");
     }
}
Output :
 Print message to console....
 Print message to console....

Java Lambda Expression with Multiple Parameters:

interface Addable{  
    int add(int a,int b);  
}  
public class JLEExampleMultipleParameters {

 public static void main(String[] args) {
  
     // without lambda expression
  Addable addable = new Addable() {
   @Override
   public int add(int a, int b) {
    return a + b;
   }
  };
  addable.add(10, 20);
  
  // with lambda expression
   // Multiple parameters in lambda expression  
        Addable withLambda = (a,b)->(a+b);  
        System.out.println(withLambda.add(10,20));  
          
        // Multiple parameters with data type in lambda expression  
        Addable withLambdaD = (int a,int b) -> (a+b);  
        System.out.println(withLambdaD.add(100,200));  
 }
 
}

Java Lambda Expression with Multiple Statements in a Body:

interface IAvarage{  
    double avg(int[] array);  
}  
public class JLEExampleMultipleStatements {

    public static void main(String[] args) {
  
        // without lambda expression, IAvarage implementation using anonymous class  
         IAvarage avarage = new IAvarage() {
            @Override
            public double avg(int[] array) {
                double sum = 0;
                int arraySize = array.length;
    
                System.out.println("arraySize : " + arraySize);
                for (int i = 0; i < array.length; i++) {
                    sum = sum + array[i]; 
                } 
                System.out.println("sum : " + sum);
    
                return (sum/ arraySize);
           }
        };
        int[] array = {1,4,6,8,9};
        System.out.println(avarage.avg(array));
  
        // with a lambda expression
        // You can pass multiple statements in lambda expression 
  
        IAvarage withLambda = (withLambdaArray) -> {
            double sum = 0;
            int arraySize = withLambdaArray.length;
   
            System.out.println("arraySize : " + arraySize);
            for (int i = 0; i < withLambdaArray.length; i++) {
                sum = sum + withLambdaArray[i]; 
            }
            System.out.println("sum : " + sum);
   
            return (sum/ arraySize);
       };
  
        int[] withLambdaArray = {1,4,6,8,9};
        System.out.println(withLambda.avg(withLambdaArray)); 
    }
}

Related Java Interview Articles

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments