概述
官网对lambda表达式的描述
> 官网:https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.
匿名类的一个问题是,如果匿名类的实现非常简单,例如只包含一个方法的接口,那么匿名类的语法可能会显得笨拙和不清楚。在这些情况下,您通常会尝试将功能作为参数传递给另一个方法,例如当有人单击按钮时应该采取什么操作。 Lambda 表达式使您能够做到这一点,将功能视为方法参数,或将代码视为数据。
> 描述中包含了三层含义
- lambda表达式是对匿名类的简化
- lambda使用的前提
- 一个接口
- 接口中包含一个方法
- lambda表达式的理解:将功能作为参数传递给另一个方法
示例代码
- 创建并开启一个线程,使用匿名内部类的方式实现Runnable,重写run方法
public static void main(String[] args) {
new Thread(new Runnable() { // 匿名内部类
@Override
public void run() {
System.out.println("我是线程开启执行的代码");
}
}).start();
}
```
- Runnable接口中只有一个抽象方法run。用lambda表达式改写
// @FunctionalInterface
// public interface Runnable {
// public abstract void run();
// }
public static void main(String[] args) {
new Thread(() -> System.out.println("我是线程开启执行的代码")).start();
}
```
语法
基本语法
> 从上述案例中,使用lambda表达式是对Runnable接口中的run方法进行了重写
>
> 格式:(抽象方法的参数列表) -> {重写的代码}
示例代码
> 删除集合中大于3的元素
- 匿名内部类
List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5));
list.removeIf(new Predicate<Integer>() {
@Override
public boolean test(Integer i) {
return i > 3;