8.2.3 使用Lambda表达式遍历Iterator
8.2.3 使用Lambda表达式遍历Iterator
Iterator在Java8中新增的forEachRemaining方法
Java8为Iterator新增了一个forEachRemaining方法:
| Iterator的forEachRemaining方法 | 描述 |
|---|---|
default void forEachRemaining(Consumer<? super E> action) |
Performs the given action for each remaining element until all elements have been processed or the action throws an exception. |
该方法所需的参数Consumer是函数式接口,当程序调用Iterator的forEachRemaining遍历集合元素时,程序会依次将集合元素传给Consumer的acept方法:
Consumer的accept方法 |
描述 |
|---|---|
void accept(T t) |
Performs this operation on the given argument. |
forEachRemaining方法的参数可以是Lambda表达式或者匿名内部类
因为forEachRemaining()方法参数Consumer是函数式接口,所以:
- 可以传给该方法一个
Lambda表达式作为参数, - 也可以传入一个匿名内部类作为参数。
不过lambda表达式比匿名内部类代码量比较少。
程序 Iterator新增的forEachRemaining方法来遍历集合
如下程序示范了使用Lambda表达式来遍历集合元素。
1 | import java.util.*; |
运行效果如下
1 | Lambda表达式迭代集合元素:1 |