Search code examples
javacollections

Iterating HashMap in order


I have a HashMap.

It has 100s of millions of observations.

What's the best way to iterate over the elements of the HashMap, in numerical order of the keys?

I considered changing to TreeMap, but did not do that since it may actually increase the load in creating the Map (as TreeMap is O(n), HashMap is O(1)).


Solution

  • With Java 8 you could use something similar to the following:

    import static java.util.Comparator.comparing;
    
    map.entrySet().stream()
       .sorted(comparing(Entry::getKey))
       .forEach(e -> doSomethingWithTheEntry(e));
    

    That will obviously involve sorting the unsorted keys, which will come at a cost. So you need to decide whether you want to pay the cost upfront with a TreeMap or when required and keep using a HashMap.