Java Lambda表达式上下文
2018-03-18 17:24 更新
Java Lambda表达式上下文
lambda表达式可以只在以下四种环境中使用。
- 赋值上下文
- 方法调用上下文
- 返回上下文
- 转换上下文
赋值上下文
lambda表达式可以显示在赋值运算符的右侧。
public class Main {
public static void main(String[] argv) {
Calculator iCal = (x,y)-> x + y;
System.out.println(iCal.calculate(1, 2));
}
}
@FunctionalInterface
interface Calculator{
int calculate(int x, int y);
}
上面的代码生成以下结果。

方法调用上下文
我们可以使用lambda表达式作为方法或构造函数的参数。
public class Main {
public static void main(String[] argv) {
engine((x,y)-> x / y);
}
private static void engine(Calculator calculator){
long x = 2, y = 4;
long result = calculator.calculate(x,y);
System.out.println(result);
}
}
@FunctionalInterface
interface Calculator{
long calculate(long x, long y);
}
上面的代码生成以下结果。

返回上下文
我们可以在return语句中使用lambda表达式,其目标类型在方法返回类型中声明。
public class Main {
public static void main(String[] argv) {
System.out.println(create().calculate(2, 2));
}
private static Calculator create(){
return (x,y)-> x / y;
}
}
@FunctionalInterface
interface Calculator{
long calculate(long x, long y);
}
上面的代码生成以下结果。

转换上下文
我们可以使用一个lambda表达式前面加一个cast。在转换中指定的类型是其目标类型。
public class Main {
public static void main(String[] argv) {
engine((IntCalculator) ((x,y)-> x + y));
}
private static void engine(IntCalculator calculator){
int x = 2, y = 4;
int result = calculator.calculate(x,y);
System.out.println(result);
}
private static void engine(LongCalculator calculator){
long x = 2, y = 4;
long result = calculator.calculate(x,y);
System.out.println(result);
}
}
@FunctionalInterface
interface IntCalculator{
int calculate(int x, int y);
}
@FunctionalInterface
interface LongCalculator{
long calculate(long x, long y);
}
上面的代码生成以下结果。

以上内容是否对您有帮助:

免费 AI IDE


更多建议: