How to initialize an array using lambda expression in Java?


An array is a fixed size element of the same type. The lambda expressions can also be used to initialize arrays in Java. But generic array initializes cannot be used.

Example-1

interface Algebra {
   int operate(int a, int b);
}
public class LambdaWithArray1 {
   public static void main(String[] args) {
      // Initialization of an array in Lambda Expression
      Algebra alg[] = new Algebra[] {
                                        (a, b) -> a+b,
                                        (a, b) -> a-b,
                                        (a, b) -> a*b,
                                        (a, b) -> a/b
                                    };
      System.out.println("The addition of a and b is: " + alg[0].operate(30, 20));
      System.out.println("The subtraction of a and b is: " + alg[1].operate(30, 20));
      System.out.println("The multiplication of a and b is: " + alg[2].operate(30, 20));
      System.out.println("The division of a and b is: " + alg[3].operate(30, 20));
   }
}

Output

The addition of a and b is: 50
The subtraction of a and b is: 10
The multiplication of a and b is: 600
The division of a and b is: 1


Example-2

interface CustomArray<V> {
   V arrayValue();
}
public class LambdaWithArray2 {
   public static void main(String args[]) {
      // Initilaize an array in Lambda Expression
      CustomArray<String>[] strArray = new CustomArray[] {
                                                     () -> "Adithya",
                                                     () -> "Jai",
                                                     () -> "Raja",
                                                     () -> "Surya"
                                                 };
      System.out.println(strArray[0].arrayValue());
      System.out.println(strArray[1].arrayValue());
      System.out.println(strArray[2].arrayValue());
      System.out.println(strArray[3].arrayValue());
   }
}

Output

Adithya
Jai
Raja
Surya

Updated on: 11-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements