8.2.1 使用Lambda表达式遍历集合
8.2.1 使用Lambda表达式遍历集合
函数式接口
所谓函数式接口就是只有一个抽象方法的接口,可以通过Lambda表达式来创建函数式接口实例.
Iterable接口的forEach方法
Java 8为Iterable接口新增了一个forEach(Consumer action)的默认方法,该方法的方法签名如下
| Iterable的forEach方法签名 | 描述 |
|---|---|
default void forEach(Consumer<? super T> action) |
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. |
这个forEach方法所需参数的类型Consumer是一个函数式接口。
而Iterable接口是Collection接口的父接口,因此Collection集合也可直接调用 继承 得到的forEach方法。
Consumer函数式接口的accept方法
当程序调用Iterable的forEach(Consumer action)遍历集合元素时,程序会依次将集合元素传给Consumer的accept(T t)方法(accept方法是该接口中唯一的抽象方法)。
| Consumer接口的抽象方法 | 描述 |
|---|---|
void accept(T t) |
Performs this operation on the given argument. |
使用Lambda表达式来遍历集合
正因为Consumer是函数式接口,因此可以使用Lambda表达式来遍历集合元素.
程序示例
如下程序示范了使用Lambda表达式和匿名内部类方式来遍历集合元素。
1 | import java.util.*; |
运行效果:
1 | Lambda表达式 遍历:1 |
上面程序中调用了Iterable的forEach默认方法来遍历集合元素,传给该方法的参数是个Lambda表达式,该Lambda表达式的目标类型是Consumer。forEach()方法会自动将集合元素逐个地传给Lambda表达式的形参,这样Lambda表达式的代码体即可遍历到集合元素了。