java8 (jdk 1.8) 新特性 ——初步认识
1. 什么是lambda?
目前已知的是,有个箭头 ->
说一大段官方话,也没有任何意义
我们直接看代码:
之前我们创建线程是这样的
Runnable runnable = new Runnable() { @Override public void run() { System.out.println("run。。。。。。"); } }; runnable.run();
用lambda:
Runnable run2 = () -> System.out.println("run。。。。。。"); run2.run();
是不是感觉特别离谱,看不懂
别急,还有更离谱的
很常见的一个例子,比较两个整数的大小
之前是这样写的
Comparator<Integer> myCom = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return Integer.compare(o1, o2); } }; int compare = myCom.compare(12, 20); int compare1 = myCom.compare(20, 12); int compare2 = myCom.compare(20, 20); System.out.println(compare); System.out.println(compare1); System.out.println(compare2); }
用lambda:
Comparator<Integer> myCom = (o1, o2) -> Integer.compare(o1, o2); int compare = myCom.compare(12, 20); int compare1 = myCom.compare(20, 12); int compare2 = myCom.compare(20, 20); System.out.println(compare); System.out.println(compare1); System.out.println(compare2);
甚至还可以这样 (这个是方法引用)
Comparator<Integer> myCom = Integer::compare; int compare = myCom.compare(12, 20); int compare1 = myCom.compare(20, 12); int compare2 = myCom.compare(20, 20); System.out.println(compare); System.out.println(compare1); System.out.println(compare2);
第一个数比第二个数
大 :返回 1
小:返回 -1
相等:返回 0
刚接触是不是黑人问号,这是什么玩意
很好,到这,你认识到了lambda 一个缺点,可阅读性差 ,优点 代码简洁
小结:看到 -> lambda 看到 : : 方法引用
2. lamdba 语法
-
基本语法
1. 箭头操作符 -> 或者叫做lambda 操作符
2. 箭头操作符将lambda 表达式拆分成两部分
左侧:Lambda 表达式的参数列表
右侧:Lambda 表达式中所需执行的功能 , 即 Lambda 体
3. 语法格式
语法格式1:无参数,无返回值
-
() -> system.out.println("Hello Lambda")
前边线程的那个例子就是
语法格式2:有一个参数 无返回值
(x)-> System.out.println(x);
若只有一个参数可以省略不写
x-> System.out.println(x);
之前的写法,没有使用lambda
Consumer<String> consumer = new Consumer<String>() { @Override public void accept(String s) { System.out.println("输出的值:"+s); } }; consumer.accept("今天不想emo了");
使用lambda
Consumer<String> consumer = s -> System.out.println("输出的值:"+s); consumer.accept("今天不想emo了");
语法格式3:有两个以上参数 ,并且lambda体有多条语句,有返回值
Comparator<Integer> myCom = (o1, o2) -> { System.out.println("其他语句"); return Integer.compare(o1, o2); };
语法格式4 lambda体中只有一条语句,return 和 大括号都可以省略不写
Comparator<Integer> com =(x,y)-> Integer.compare(x,y);
有没有发现所有的参数,都没有参数类型,之前我们写函数的时候可是要带上参数类型的
语法格式5 lambda表达式参数列表的数据类型可以省略不写,因为JVM编译器通过上下文编译推断出数据类型——类型推断
4. 函数式接口
不管上面哪一种语法格式,lambda都是需要函数式接口的支持
函数式接口:接口中只有一个抽象方法的接口 称为函数式接口
可以使用一个注解@FunctionalInterface 修饰,可以检查是否是函数式接口
我们可以看看Runnable 接口 的源码
完成的接口类代码如下
/* * Copyright (c) 1994, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTI