一、Lambda表达式的基础语法:Java8中引进了一个新的操作符"->",该操作符称为箭头操作符或Lambda操作符,箭头操作符将Lambda表达式拆分成两部分
左侧:Lambda表达式的参数列表,对应要实现的抽象方法的参数列表
右侧:Lambda表达式所需执行的功能,即Lambda体,是对接口抽象方法的功能实现(这样就需要函数式接口)
- 语法格式一:无参数,无返回值(抽象方法)
()->System.out.println(“Hello Lambda!”);
@Test
public void test1() {
int num=0;//jdl 1.7之前,必须是final
Runnable r=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Hello word!"+num);
}
};
r.run();
System.out.println("*************************");
Runnable r1=()->System.out.println("Hello Lambda!"+num);
//实现Runnable接口的run抽象方法,这里的Runnable接口是函数式接口,即接口中只有一个抽象方法的接口
r1.run();
}
- 语法格式二:有一个参数,无返回值
(x)->System.out.println(x);
@Test
public void test2() {
Consumer<String> con=(x)->System.out.println(x);
con.accept("kkkkkkkkkkkk");
}
-
语法格式三:若只有一个参数,小括号可以不写,但习惯上写 x->System.out.println(x);
-
语法格式四:有两个及以上的参数,有返回值,并且Lambda体中有多条语句
(x,y)->{System.out.println(“多条语句”);
return Integer.compare(x, y);
};
@Test
public void test4() {
Comparator<Integer> com=(x,y)->{
System.out.println("多条语句");
return Integer.compare(x, y);
};
}
- 语法格式五:若Lambda体中只有一条语句,return和大括号都可以省略不写 (x,y)->Integer.compare(x, y);
@Test
public void test5() {
Comparator<Integer> com=(x,y)->Integer.compare(x, y);
}
- 语法格式六:Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器能通过上下文推断出数据类型,即“类型推断”
public void test6() {
//类型推断
String [] strings={"aaa","bbb","ccc"};
//分开写就会出错,因为JVM不能通过上下文推断类型
List<String> list=new ArrayList<>();//后面的尖括号不用写类型,因为可以通过前面推断出数据类型
show(new HashMap<>());//可以推断出集合里元素的数据类型
}
public void show(Map<String, Integer> map) {
}
二、Lambda表达式需要“函数式接口”的支持
函数式接口:接口中只有一个抽象方法的接口。可以使用注解@FunctionalInterface修饰,可以检查是否是函数式接口
@FunctionalInterface
public interface MyPredicate <T>{
public boolean test(T t);
}
有了@FunctionalInterface修饰之后,接口就只能写一个抽象方法,不然会出错。
写一个程序练习一下
//需求:对一个数进行运算
@Test
public void test7() {
Integer num=operation(100, (x)->x*x);
System.out.println(num);
System.out.println(operation(200, (y)->y+100));
}
public Integer operation(Integer num,MyFun mf) {
return mf.getValue(num);
}
@FunctionalInterface
public interface MyFun {
public Integer getValue(Integer num);
}