如何在 Java 中使用 lambda 表示式初始化一個數組?


陣列是一個固定大小的相同型別的元素。lambda 表示式可用於在 Java 中初始化陣列。但無法使用通用陣列初始化。

示例 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));
   }
}

輸出

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


示例 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());
   }
}

輸出

Adithya
Jai
Raja
Surya

更新於:2020 年 7 月 11 日

2K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲取認證

開始學習
© . All rights reserved.