0

I have a HashMap defined as such:

public Map<Integer, String> staticBlockPositions = new HashMap<Integer, String>();

I am iterating over the map by getting each key, like this:

for (Integer key : blockPositions.keySet()) {
    System.out.println(key);
}

My question is, can I rely on the value of key to always be in ascending order. So if my HashMap looks something like this:

{
    4: "abc123",
    1: "def456",
    11: "qwe789",
    10: "iop019"
}

(I know this is JSON format, this is just so you get an idea of the data set).

Will my loop always output

1
4
10
11

regardless of the order of my data?

Important to note, the order in which the keys are add is completely random, and I cannot control what key is added when.

This is for a Tetris style game, so getting the keys in ascending order is a must.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
BigSpicyPotato
  • 739
  • 5
  • 18

3 Answers3

8

Quoting the Javadoc:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

There is no special case for integer keys. You simply can't rely upon the order.

If you want the keys to be in ascending order, use an implementation of SortedMap, like TreeMap.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • TreeMap is what i was looking for. Thanks – BigSpicyPotato Apr 03 '17 at 15:06
  • While what you say is absolutely correct, the order of the keys in a `HashMap` is predictable *to a limited degree*; see http://stackoverflow.com/a/2144822/139985. (But this fact is not something that it is sane to try to rely on in an application.) – Stephen C Apr 03 '17 at 15:15
0

In addition to what @AndyTurner stated about HashMap not guaranteeing order, it appears that TreeMap provides the functionality you are looking for.

Brett Okken
  • 6,210
  • 1
  • 19
  • 25
0

No,

  1. To maintain sorted order, use TreeMap.

  2. To maintain insertion order, use LinkedHashMap.

Ajay V
  • 523
  • 5
  • 11