如何在 Java 中的 lambda 表达式中编写条件表达式?
**条件运算符**用于在 Java 中编写**条件表达式**。它也被称为**三元运算符**,因为它有三个操作数,如**布尔条件**、**第一个表达式**和**第二个表达式**。
我们还可以在下面的程序中在 lambda 表达式中编写一个条件表达式。
示例
interface Algebra {
int substraction(int a, int b);
}
public class ConditionalExpressionLambdaTest {
public static void main(String args[]) {
System.out.println("The value is: " + getAlgebra(false).substraction(20, 40));
System.out.println("The value is: " + getAlgebra(true).substraction(40, 10));
}
static Algebra getAlgebra(boolean reverse) {
Algebra alg = reverse ? (a, b) -> a - b : (a, b) -> b - a; // conditional expression
return alg;
}
}输出
The value is: 20 The value is: 30
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP