JAVA8中引入了一个新的操作符“->”,该操作符称为箭头操作符或Lambda操作符,箭头操作符将Lambda表达式拆分成两部分
左侧: Lambda表达式的参数列表
右侧: Lambda表达式中所需要执行的功能,即Lambda体
所谓Lambda表达式就是接口的实现的一种方式,Lambda表达式的参数列表就是接口中抽象方法的参数列表,Lambda表达式中所需要执行的功能就是接口中抽象方法具体实现要执行的功能
语法格式一 :实现的接口无参 无返回值
左侧直接写() ,右侧是实现接口的功能
() -> System.out.println("Hello Lambda");
以Runable接口为例
@Test
public void test1(){
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Hello World");
}
};
r1.run();
System.out.println("--------------------------------");
Runnable r2 = () -> System.out.println("Hello Lambda");
r2.run();
}
运行结果:
Hello World
--------------------------------
Hello Lambda
语法格式二 :实现的接口有一个参数 无返回值
(X) -> System.out.println(x);
以Consumer接口为例
@Test
public void test2(){
Consumer<String> con = (x) -> System.out.println(x);
con.accept("Hello Lambda");
}
运行结果:
Hello Lambda
语法格式三 :若实现的接口有且只有一个参数 左侧()可以省略
X -> System.out.println(x);
@Test
public void test3(){
Consumer<String> con = x -> System.out.println(x);
con.accept("Hello Lambda");
}
运行结果:
Hello Lambda
语法格式四 :有两个及以上的参数,有返回值,并且Lambda体中有多条语句
Comparator<Integer> com = (x, y) -> {
System.out.println("Hello Lambda");
return Integer.compare(x,y);
以Comparator接口为例
@Test
public void test4() {
Comparator<Integer> com = (x, y) -> {
System.out.println("Hello Lambda");
return Integer.compare(x,y);// Comparator类的抽象方法 int compare(T o1, T o2);
};
}
语法格式五:有两个以上的参数,有返回值,并且Lambda体中只有一条语句 {}和return 可以省略
(x, y) -> Integer.compare(x,y);
@Test
public void test5() {
Comparator<Integer> com = (x, y) -> Integer.compare(x,y);
}
语法格式六:Lambda 表达式的参数列表的数据类型可以省略不写 ,因为jdk1.8 JVM编译器可以通过上下文推断出数据类型,即“类型推断”
( x, y) -> Integer.compare(x,y);
@Test
public void test6() {
//省略前
Comparator<Integer> com = (Integer x,Integer y) -> Integer.compare(x,y);
//省略后
Comparator<Integer> com1 = (x, y) -> Integer.compare(x,y);
//比如 以下都是通过上下文推断出类型
String[] strs = {"aaa","bbb","ccc"};
List<String> list = new ArrayList<>();
show(new HashMap<>());
}
public void show(Map<String,Integer> map){
}
总结:
上联:左右遇一括号省
下联:左侧推断类型省
横批: 能省则省
Lambda 表达式需要“函数式接口”的支持
函数式接口:接口中只有一个抽象方法的接口,称为函数式接口
可以使用注解@FunctionalInterface 修饰,声明只能有一个抽象方法,可以检查是否为函数式接口
需求 对一个数进行运算
使用Lambda表达式,创建一个函数式接口
@FunctionalInterface
public interface MyFun {
public Integer getValue(Integer num);
}
@Test
public void test7(){
Integer num = opration(100, x -> x + 200);//加法
System.out.println(num);
System.out.println(opration(100, x -> x*x));//乘法
}
/**
* @param num 对一个数进行运算
* @param myFun 进行什么运算
* @return
*/
public Integer opration(Integer num,MyFun myFun){
return myFun.getValue(num);
}
运行结果:
300
10000