由于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);
});
源碼如下:和傳統(tǒng)方法3區(qū)別不大,套殼悔醋。
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.
默認(rèn)實(shí)現(xiàn)不會(huì)保證此方法的同步或原子屬性狭瞎。 提供原子性保證的任何實(shí)現(xiàn)都必須覆蓋此方法并記錄其并發(fā)屬性妄帘。
插個(gè)眼妆毕。并發(fā)沒看趾诗。
- 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());