如何在Java中使用Lambda表达式初始化数组?

数组是相同类型的固定大小的元素。lambda表达式也可以用于初始化Java中的数组。但是不能使用通用数组初始化。

示例1

interface Algebra {
   int operate(int a, int b);
}
public class LambdaWithArray1 {
   public static void main(String[] args) {
      //在Lambda表达式中初始化数组
      Algebra alg[] = new Algebra[] {
                                        (a, b) -> a+b,
                                        (a, b) -> a-b,
                                        (a, b) -> a*b,
                                        (a, b) -> a/b
                                    };
      System.out.println("a和b的加法是: " + alg[0].operate(30, 20));
      System.out.println("a和b的减法是: " + alg[1].operate(30, 20));
      System.out.println("a和b的乘法是: " + alg[2].operate(30, 20));
      System.out.println("a和b的除法是: " + alg[3].operate(30, 20));
   }
}

输出结果

a和b的加法是: 50
a和b的减法是: 10
a和b的乘法是: 600
a和b的除法是: 1


示例2

interface CustomArray<V> {
   V arrayValue();
}
public class LambdaWithArray2 {
   public static void main(String args[]) {
      //在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());
   }
}

输出结果

Adithya
Jai
Raja
Surya