4

Is there a way to compact a HashMap in the sense that you can with an ArrayList through its trimToSize() method?

One way I can think of is to iterate through all of the entries in the present map and populate a new one, then replace the original with the new one.

Is there a better way to accomplish this?

Scheintod
  • 7,953
  • 9
  • 42
  • 61
bguiz
  • 27,371
  • 47
  • 154
  • 243
  • If you're worried about HashMap taking extra space, pass a higher load factor when creating it. – Jagat Oct 13 '11 at 19:47

2 Answers2

6

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • The idea of iterating manually is intriguing! Do you need special gloves to grip the entries of the hashmap? :-) – Stephen C Oct 13 '11 at 06:54
  • @JBNizet: Yes it does - see `HashMap.Entry`, which has a final `hash` field. Have I misunderstood something? – Jon Skeet Oct 13 '11 at 07:26
  • No you haven't. I missed the hash field in Entry. My mistake. – JB Nizet Oct 13 '11 at 07:34
  • This does not exactly answer the question. You are creating a new map. The original map is not compacted in the same sense as `ArrayList.trimToSize()` – PoweredByRice Mar 06 '17 at 03:23
  • @PoweredByRice: The question is "Is there a way to compact a HashMap" and my answer is "I don't think there's any way of performing a "trim" operation in the current API". – Jon Skeet Mar 06 '17 at 04:20
-1

If you use the trove library instead this has support for hash map and hash set trimming (see THashMap object, compact method) and best of all, automatically trims on removal of objects when the map becomes too sparse. This should be quicker than building a new map using the standard java HashMap implementation as (presumably) it doesn't have to reorder the objects according to their hashcode, but can just use the order it already knows.