Commits

Илья Казначеев committed 22792ab

Do not use entrySet().filter() because it's very unsafe; filter imperatively

Comments (0)

Files changed (2)

src/main/java/ru/yandex/bolts/collection/impl/AbstractMapF.java

 import java.io.Serializable;
 import java.util.AbstractMap;
 import java.util.Map;
-import java.util.NoSuchElementException;
 
 import ru.yandex.bolts.collection.CollectionF;
 import ru.yandex.bolts.collection.CollectionsF;
     public MapF<K, V> filterEntries(Function1B<Entry<K, V>> p) {
         if (isEmpty()) return this;
 
-        return newMap(entrySet().filter(p));
+        MapF<K, V> result = newMutableMap();
+        for (Entry<K, V> e : entrySet()) {
+            if (p.apply(e)) result.put(e.getKey(), e.getValue());
+        }
+        return result;
     }
 
     @Override

src/main/java/ru/yandex/bolts/collection/impl/AbstractMapFTest.java

         assertEquals(CollectionsF.map(2, "2", 11, "11"), n);
     }
 
+    public void testFilterStinky() {
+        Object stinky = new Object() {
+            public int hashCode() {
+                throw new UnsupportedOperationException("I stink");
+            }
+        };
+        MapF<Integer, Object> mapToFilter = Cf.hashMap();
+        mapToFilter.put(1, stinky);
+        mapToFilter.put(-3, "flower");
+        mapToFilter.put(2, 2);
+        mapToFilter.put(-1, mapToFilter);
+        assertEquals(set(1, 2), mapToFilter.filterKeys(Cf.Integer.gtF(0)).keySet());
+        assertEquals(set(-1, -3), mapToFilter.filterKeys(Cf.Integer.ltF(0)).keySet());
+    }
+
     public void testMapValues() {
         MapF<Integer, String> n = map123().mapValues(new Function<String, String>() {
             public String apply(String s) {