8.2.3 使用Lambda表达式遍历Iterator

8.2.3 使用Lambda表达式遍历Iterator

Iterator在Java8中新增的forEachRemaining方法

Java8Iterator新增了一个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是函数式接口,当程序调用IteratorforEachRemaining遍历集合元素时,程序会依次将集合元素传给Consumeracept方法:

Consumeracept方法 描述
void accept(T t) Performs this operation on the given argument.

forEachRemaining方法的参数可以是Lambda表达式或者匿名内部类

因为forEachRemaining()方法参数Consumer是函数式接口,所以:

  • 可以传给该方法一个Lambda表达式作为参数,
  • 也可以传入一个匿名内部类作为参数.

不过lambda表达式比匿名内部类代码量比较少.

程序 Iterator新增的forEachRemaining方法来遍历集合

如下程序示范了使用Lambda表达式来遍历集合元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.util.*;
import java.util.function.Consumer;

public class IteratorEach {
public static void main(String[] args) {
// 创建集合、添加元素的代码与前一个程序相同
Collection<String> collection = new HashSet<String>();
collection.add("1");
collection.add("2");
collection.add("3");
// 获取books集合对应的迭代器
Iterator<String> iterator = collection.iterator();
// 使用Lambda表达式(目标类型是Comsumer)来遍历集合元素
iterator.forEachRemaining(str -> System.out.println("Lambda表达式迭代集合元素:" + str));
System.out.println("----------------------------");
// 重新获取迭代器
iterator = collection.iterator();
iterator.forEachRemaining(new Consumer<String>() {
@Override
public void accept(String str) {
System.out.println("匿名内部类迭代集合元素:" + str);
}
});
}
}

运行效果如下

1
2
3
4
5
6
7
Lambda表达式迭代集合元素:1
Lambda表达式迭代集合元素:2
Lambda表达式迭代集合元素:3
----------------------------
匿名内部类迭代集合元素:1
匿名内部类迭代集合元素:2
匿名内部类迭代集合元素:3