02.Lambda表达式

02.Lambda表达式

什么是lambda表达式?

Lambda 表达式(lambda expression)是一个匿名函数,将代码像数据一样传递。Lambda表达式可以表示闭包

基础语法

Java8中引入了新的操作符->该操作符称为箭头操作符或Lambda操作符

箭头操作符将Lambda表达式拆分成两部分:

  • 左侧:Lambda表达式的参数列表

  • 右侧:Lambda表达式中所需执行的功能,即Lambda体

语法格式一:

无参数,无返回值

()->System.out.println("Hello Lambda!");

int num = 0;	//JDK 1.7及以前需要用final修饰 
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello World!" + num);//即使是JDK1.8 也不能使用num++ num不能被改变
    }
};
runnable.run();

Runnable r = ()-> System.out.println("Hello Lambda!"+ num);//不能使用num++ num不能被改变
r.run();

语法格式二:

有一个参数,并且无返回值

(x)->System.out.println(x);

Consumer<String> con = (x) -> System.out.println(x);
con.accept("Hello Lambda!");

语法格式三:

若只有一个参数,小括号可省略不写

x -> System.out.println(x);

Consumer<String> con = x -> System.out.println(x);
con.accept("Hello Lambda!");

语法格式四:

有两个及以上的参数,有返回值,并且 Lambda 体中有多条语句

Comparator<Integer> com = (x, y) -> {
    System.out.println("Hello Lambda!");
    return Integer.compare(x, y);
};
int compare = com.compare(3, 4);
System.out.println(compare);

语法格式五:

若Lambda体中只有一条语句,return和大括号都可以省略不写

Comparator com = (x, y) -> Integer.compare(x, y);

Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
int compare = com.compare(3, 4);
System.out.println(compare);

语法格式六:

Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器可以通过上下文推断出【数据类型】,即"类型推断"

(Integer x, Integer y) -> Integer.compare(x, y);

Comparator<Integer> com = (Integer x, Integer y) -> Integer.compare(x, y);
int compare = com.compare(3, 4);
System.out.println(compare);

类型推断:

场景一:

String[] arr = {"aaa", "bbb", "ccc"}; //正常


String[] arr;

arr = {"aaa", "bbb", "ccc"}; //报错

场景二:

List list = new ArrayList<>();

注意事项:

  • Lambda表达式需要"函数式接口"的支持

什么是函数式接口?

函数式接口: 接口中只有一个抽象方法,称为函数式接口。可以使用@FunctionalInterface修饰。

@FunctionalInterface用于指定当前接口为函数式接口,若接口中存在多个抽象方法,该接口编译时报错

猜你喜欢

转载自www.cnblogs.com/jwhu/p/12977000.html