573

I'm using a HashMap. When I iterate over the map, the data is returned in (often the same) random order. But the data was inserted in a specific order, and I need to preserve the insertion order. How can I do this?

double-beep
  • 5,031
  • 17
  • 33
  • 41
realtebo
  • 23,922
  • 37
  • 112
  • 189

2 Answers2

1240

LinkedHashMap is precisely what you're looking for.

It is exactly like HashMap, except that when you iterate over it, it presents the items in the insertion order.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 14
    according to java doc it says: This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map.¿¿¿¿¿ NORMALLY ????? what does it mean? the order insertion is not garantee.... – Xenione Feb 23 '14 at 12:53
  • 21
    @Xenione: You get to choose between insertion order and access order. See the last argument to http://bit.ly/1jZXlCl – NPE Feb 23 '14 at 12:58
  • 12
    @Xenione [Note that insertion order is not affected if a key is re-inserted into the map], when a key is put twice the second put doesn't change the order so iterating order is not exactly the insert order because of unicity of keys; normally means if keys are unique – Nahuel Fouilleul Nov 20 '15 at 14:18
  • 1
    constructors give a "insert order" Map, but constructor (int,float,boolean), if third argument is true allows to create "access order" LinkedHashMap in this case the call of get will affect order, the order is the least accessed first – Nahuel Fouilleul Nov 20 '15 at 14:35
  • This makes using `java.util.Comparator` with `java.util.Collections.sort()` explicitly unnecessary and thank you for providing very helpful information. – Mushy Jul 11 '16 at 14:09
78

HashMap is unordered per the second line of the documentation:

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.

Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. Take a look on javapractices.com's guide on Choosing the right Collection.

bruno
  • 2,213
  • 1
  • 19
  • 31
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120