一、Lambda表达式
Lambda是一个匿名函数,我们可以把Lambda表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。使代码更简洁更灵活。
二、Lambda表达式的基础语法
Java8中引入了一个新的操作符->
,这个操作符称为箭头操作符或者Lambda操作符,箭头操作符将Lambda表达式拆分成了两部分。
操作符左侧:Lambda表达式的参数列表
操作符右侧:Lambda表达式中所需执行的功能,即Lambda体。
* 无参数,无返回值
() -> System.out.println("Hello Lambda")
我们在局部内部类中应用Lambda表达式,展示一下接口无参数,无返回值的使用
原代码:
public void test1() {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello World");
}
};
r.run();
}
使用Lambda表达式:
public void test(){
Runnable lamR = () -> System.out.println("Hello World");
lamR.run();
}
* 有一个参数,无返回值
若只有一个参数,小括号可以省略不写。
用Lambda表达式实现Consumer.accept(T t);方法
原接口:
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
}
Lambda实现:
public void test2() {
Consumer<String> con = (x) -> System.out.print(x);
con.accept("Lambda一个参数,无返回值");
}
* 有两个以上的参数,有返回值,并且Lambda体中有多条语句
如果有多条语句,Lambda必须使用大括号({}
)。如果Lambda体中只有一条语句,return和大括号都可以省略不写。
使用Lambda表达式实现Comarator.compare(T o1, T o2);接口。
原来的匿名内部类写法:
Comparator<Integer> com = new Comparator<Integer>(){
@Override
public int compare(Integer o1,Integer o2){
return Integer.compare(o1,o2);
};
}
Comparator<Integer> com = (x,y) ->{
System.out.println("函数式接口");
return Integer.compare(x, y);
};
省略return 以及 大括号的写法:
Comparator<Integer> comp = (x,y) -> Integer.compare(x, y);
Lambda表达式的参数列表的数据类型可以省略不写,因为JVM编译器可以通过上下文推断出数据类型,即“类型推断”
二、函数式接口
Lambda需要“函数式接口”的支持,函数式接口:接口中只有一个抽象方法的接口,称为函数式接口。可以使用注解 @FunctionalInterface
修饰,检查是否是函数式接口。
需求练兵
- 定义一个函数式接口:
@FunctionalInterface
public interface MyFun {
public Integer getInteger(Integer num);
}
- 编写测试类,用Lambda实现定义的函数式接口:
public class LambdaTest {
//对一个数进行运算
@Test
public void test4() {
Integer num = operation(100,(x) -> x * x);
System.out.println(num);
System.out.println(operation(200, (y) -> y + 200));
}
public Integer operation(Integer num,MyFun mf) {
return mf.getInteger(num);
}
}