Search code examples
javacachingiteratorhashmaplinkedhashmap

Shrink LinkedHashMap in Java


How can you shrink a LinkedHashMap? I overrode the removeEldestEntry method, but this method is only called once when a new value is inserted. So there is no change of making the map smaller this way.

The LinkedHashMap only gives my a normal Iterator and doesn't have any removeLast or listIterator method, so how can you find the last, say 1000, entries and remove them?

The only way I can think of is iterating through that whole thing. But that can take ages...

Creating a new map every time I want to remove only a few elements will also destroy the memory.

Maybe remove the first values of the Iterator and then reinserted them, when the maxSize was reduced in the removeEldestEntry method. Then the reinserting would kick out the oldest values. This is very ugly code... Any better ideas?

EDIT: Sry the iteration order is oldest to youngest. So it's easy


Solution

  • The iterator will iterate from oldest to youngest for LinekdHashMap. You if you want to shrink the LinkedHashMap to a size you can use the following.

    Map<K,V> lhm =
    int desiredSize = 
    for(Iterator iter = lhm.keySet().iterator();iter.hasNext()) {
       if(lhm.size() <= desiredSize) break;
       iter.next();     //required else IllegalStateException since current=null 
       iter.remove();
    }
    

    This should take about 20 ns per entry removed.