Iterator<Entry<V>> () { ObjectIterator<Int2ObjectMap.Entry<MyReference<V>>> entryIterator = myMap.int2ObjectEntrySet().iterator(); return new Iterator<Entry<V>>() { private Entry<V> nextVEntry; private int lastReturned; { nextAliveEntry(); } @Override public boolean hasNext() { return nextVEntry != null; } @Override public Entry<V> next() { if (!hasNext()) throw new NoSuchElementException(); Entry<V> result = nextVEntry; lastReturned = result.getKey(); nextAliveEntry(); return result; } private void nextAliveEntry() { while (entryIterator.hasNext()) { Int2ObjectMap.Entry<MyReference<V>> entry = entryIterator.next(); MyReference<V> ref = entry.getValue(); V v = ref.get(); if (v == null) { continue; } int key = entry.getIntKey(); nextVEntry = new SimpleEntry<>(key, v); return; } nextVEntry = null; } @Override public void remove() { myMap.remove(lastReturned); } }; }