由于HashMap->Map->Collection->Iterable
- iterator()
Iterator it = x.iterator();
while (x.hasNext()){
(.....)(x.next());
}
- (jdk1.8后)forEach()
default void forEach(BiConsumer<? super K,? super V> action)
Performs the given action for each entry in this map until all entries have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of entry set iteration (if an iteration order is specified.) Exceptions thrown by the action are relayed to the caller.
map.forEach((k, v) -> {
System.out.println(k + ":" + v);
});
源码如下:和传统方法3区别不大,套壳。
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);
}
}
The default implementation makes no guarantees about synchronization or atomicity properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties.
默认实现不会保证此方法的同步或原子属性。 提供原子性保证的任何实现都必须覆盖此方法并记录其并发属性。
插个眼。并发没看。
- for(:)
老方法。
entrySet() Returns: a set view of the mappings contained in this map
for (Map.Entry<K, V> entry : map.entrySet())
action.accept(entry.getKey(), entry.getValue());