forEach方法介绍
default void forEach(BiConsumer<? super K,? super V> action)对此映射中的每个条目执行给定的操作,直到所有条目都被处理或操作引发异常。 除非实现类另有指定,否则按照进入设置迭代的顺序执行操作(如果指定了迭代顺序)。操作引发的异常被转发给调用者。
实现要求:
默认实现相当于,对于这个
map
:for (Map.Entry<K, V> entry : map.entrySet()) action.accept(entry.getKey(), entry.getValue());
默认实现不会保证此方法的同步或原子属性。 提供原子性保证的任何实现都必须覆盖此方法并记录其并发属性。
参数
action
- 要为每个条目执行的操作异常
NullPointerException
- 如果指定的动作为空
ConcurrentModificationException
- 如果在迭代期间发现条目被删除从以下版本开始:
1.8
测试
@Test
public void testMapForEach() {
Map<String, String> map = new HashMap<>();
map.put("name", "tom");
map.put("age", "11");
map.put("email", "xxx@126.com");
// 传统的迭代方式
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
// jdk1.8 优雅的迭代方式,看源码其实还是在传统的迭代方式上加了层壳,书写简便看起来更优雅
map.forEach((k, v) -> {
System.out.println(k + ":" + v);
});
}
源码
从源码上可以看出就是在传统的迭代方式上加了层壳,使得代码书写更加优雅
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}
jdk8离线文档
链接:https://pan.baidu.com/s/1ZPhu9mvmzVwBPN3w6694lA 密码:bpe7 ps:需要解压