18

I've set a HashMap on certain order but it is iterated on a strange order!

Please consider code below:

HashMap<String, String> map = new HashMap<String, String>();
map.put("ID", "1");
map.put("Name", "the name");
map.put("Sort", "the sort");
map.put("Type", "the type");

...

for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
}

and the result:

Name: the name
Sort: the sort
Type: the type
ID: 1

I need to iterate it in order i've put the entries. Any help will be appreciated.

AHHP
  • 2,967
  • 3
  • 33
  • 41
  • 3
    Try using LinkedHashMap http://stackoverflow.com/questions/683518/java-class-that-implements-map-and-keeps-insertion-order – Diego Pino Dec 15 '12 at 16:08
  • 1
    It is iterated in an *undefined* order. See the Javadoc. If you want ordering, use a Map implementation that provides it. – user207421 Dec 16 '12 at 00:40

2 Answers2

30

That's how HashMap works internally. Replace HashMap with LinkedHashMap which additionally remembers the order of insertion:

Map<String, String> map = new LinkedHashMap<String, String>();
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
25

The order depends on the result of the hashCode() function in the keys you are inserting which, unless you did something strange, is going to be mostly random (but consistent). What you are looking for is a sorted map such as a LinkedHashMap

Check out a little bit about how hashtables work here if you are interested in the details.

Miquel
  • 15,405
  • 8
  • 54
  • 87