Well you don't need to go through iterating manually - you can just use:
map = new HashMap<String, String>(map); // Adjust type arguments as necessary
I believe that will do all the iteration for you. It's possible that clone()
will do the same thing, but I don't know for sure.
Either way, I don't believe you're missing anything - I don't think there's any way of performing a "trim" operation in the current API. Unlike ArrayList
, such an operation would be reasonably complex anyway (as expansion is) - it's not just a case of creating a new array and performing a single array copy. The entries need to be redistributed. The benefit of getting HashMap
to do this itself internally would probably just be that the hash codes wouldn't need recomputing.