src/share/classes/java/util/LinkedHashMap.java
Print this page
rev 7360 : 8016446: Improve forEach/replaceAll for Map, HashMap, Hashtable, IdentityHashMap, WeakHashMap, TreeMap
Reviewed-by: forax, duigou, psandoz
Contributed-by: Mike Duigou <mike.duigou@oracle.com>, Remi Forax <forax@univ-mlv.fr>
@@ -23,10 +23,12 @@
* questions.
*/
package java.util;
import java.io.*;
+import java.util.function.BiConsumer;
+import java.util.function.BiFunction;
/**
* <p>Hash table and linked list implementation of the <tt>Map</tt> interface,
* with predictable iteration order. This implementation differs from
* <tt>HashMap</tt> in that it maintains a doubly-linked list running through
@@ -294,10 +296,36 @@
public void clear() {
super.clear();
header.before = header.after = header;
}
+ @Override
+ public void forEach(BiConsumer<? super K, ? super V> action) {
+ Objects.requireNonNull(action);
+ int expectedModCount = modCount;
+ for (Entry<K, V> entry = header.after; entry != header; entry = entry.after) {
+ action.accept(entry.key, entry.value);
+
+ if (expectedModCount != modCount) {
+ throw new ConcurrentModificationException();
+ }
+ }
+ }
+
+ @Override
+ public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
+ Objects.requireNonNull(function);
+ int expectedModCount = modCount;
+ for (Entry<K, V> entry = header.after; entry != header; entry = entry.after) {
+ entry.value = function.apply(entry.key, entry.value);
+
+ if (expectedModCount != modCount) {
+ throw new ConcurrentModificationException();
+ }
+ }
+ }
+
/**
* LinkedHashMap entry.
*/
private static class Entry<K,V> extends HashMap.Entry<K,V> {
// These fields comprise the doubly linked list used for iteration.