如何在 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
© .
All rights reserved.
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP