KalEl
KalEl

Reputation: 9136

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)).

Upvotes: 1

Views: 5140

Answers (3)

Eran
Eran

Reputation: 393831

You can't iterate over a HashMap in order (such as the numerical order of the keys). The iteration order in which you'll encounter the keys/values/entries of the HashMap is implementation dependent and should not be relied upon.

You can use a TreeMap for your desired iteration order. If you use a LinkedHashMap, you can iterate in the order the keys were inserted to the Map, but it's still not what you want (unless you insert the keys in numerical order).

Upvotes: 2

assylias
assylias

Reputation: 328608

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.

Upvotes: 6

NESPowerGlove
NESPowerGlove

Reputation: 5496

If your insertion order is the same order as your keys, then you could use a LinkedHashMap.

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.)

Upvotes: 2

Related Questions