/**
* Lambda expressions basically express instances of functional interfaces (An interface
* with single abstract method is called functional interface. An example is java.lang.Runnable).
* lambda expressions implement the only abstract function and therefore implement functional interfaces
*
* lambda expressions are added in Java 8 and provide below functionalities.
* · Enable to treat functionality as a method argument, or code as data.
* · A function that can be created without belonging to any class.
* · A lambda expression can be passed around as if it was an object and executed on demand.
* lambda 表达式通常是“函数式接口”的一个实例。(只包含一个抽象方法的的接口称为 函数式接口,例如 java.lang.Runnable 只包含一个 run 方法)
* lambda 表达式实现了唯一的抽象方法,因此也实现了函数式接口
* lambda 表达式在 java8 添加并提供了以下功能:
* · 可以将方法当成参数传递
* · 可以创建不属于任何类的方法
* · lambda表达式可以像传递对象一样传递,并按需执行。
*/
public class LambdaTest {
// 声明为函数式接口,不允许添加新的接口函数
@FunctionalInterface
interface FuncInterfaceA {
int single(int x);
}
@FunctionalInterface
interface FuncInterfaceB {
int add(int x, int y);
}
public static void main(String[] args) {
FuncInterfaceA fa = x -> x; // 一个参数时可以省去括号
System.out.println("x = " + fa.single(11));
FuncInterfaceB fb = (x, y) -> x + y;
System.out.println("x + y = " + fb.add( 11, 22 ));
// 优雅的开启线程
new Thread( () -> {} ) .start();
}
}
【Java脱坑指南】 lambda表达式
最新推荐文章于 2024-05-27 17:01:37 发布