src/share/classes/java/util/LinkedHashMap.java

Print this page
rev 7313 : 8016446: Improve forEach/replaceAll for Map, HashMap, Hashtable, IdentityHashMap, WeakHashMap, TreeMap
Reviewed-by: forax, duigou
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,34 @@
     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) {
+            if (expectedModCount != modCount) {
+                throw new ConcurrentModificationException();
+            }
+           action.accept(entry.key, entry.value);
+        }
+    }
+
+    @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) {
+            if (expectedModCount != modCount) {
+                throw new ConcurrentModificationException();
+            }
+           entry.value = function.apply(entry.key, entry.value);
+        }
+    }
+
     /**
      * LinkedHashMap entry.
      */
     private static class Entry<K,V> extends HashMap.Entry<K,V> {
         // These fields comprise the doubly linked list used for iteration.