Hi everyone. I have a small problem. I have a HashMap with integer keys. I need to remove elements that have the key smaller than a specified number. Can I do this in an optimized way without parsing the entire hashmap?
Doua Beri wrote:Hi everyone. I have a small problem. I have a HashMap with integer keys. I need to remove elements that have the key smaller than a specified number. Can I do this in an optimized way without parsing the entire hashmap?
With a normal HashMap I don't think you've got any better options than iterating through the Map, checking the key, and removing the ones you don't want. I'd suggest using the entrySet to do this. E.g.
It would be different if you had a SortedMap or NavigableMap (e.g. TreeMap). These are ordered according to their keys, and there are methods available to give you a view onto a sub-map, which you can then clear. E.g.
That won't be more efficient, but it's more concise. If you're not able to switch the type of map in the first place it's not much help to you, though, I'm afraid.
Joined: Sep 24, 2009
Thanks for your replies. I can change the Map type. I just need to be optimized because I will have a large Map( around 10k elements) so I'm more interested in a faster, and less resource eater solution.
I don't think there is much difference in memory usage in both solutions. That leaves speed, and there is a trade-off there:
- TreeMap is slower for general purposes but is faster than HashMap for these specific deletions - if the number of items to remove is not too large
- HashMap is faster for general purposes. Peter's code is faster but requires more Integer objects. If these Integer objects stay below 128 that doesn't matter due to the cache used with auto-boxing. Matthew's code will most likely be the slowest, as it needs to inspect each element.
If you need speed in general, TreeMap is probably not the way to go. My guess is that in most cases Peter's code will be faster than Matthew's code.
However, I think that 10k elements is nothing for these kinds of collections. TreeMap's log(10k) for retrieval / removal / insertion is around 9 times slower than the direct access of HashMap, but I doubt you will even notice - the difference will be microseconds, maybe even nanoseconds. It would be a case of premature optimization, and in that case the easiest solution should be used: SortedMap with headMap and clear.