68

I am trying figure out the order in which the values in a HashMap are/can be retrieved. Heres the code snippet for the same.

import java.util.HashMap;

public class HashMapExample {

   public static void main(String[] args) {
       HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
       hashmap.put(1, "apple" );
       hashmap.put(2, "lemon" );
       hashmap.put(3, "orange" );
       hashmap.put(4, "banana" );
       hashmap.put(5, "litchi" );
       hashmap.put(6, "mango" );
       hashmap.put(7, "papaya" );

       System.out.println(hashmap.size());

       for (String key : hashmap.values()) {
           System.out.println(key);
       }
   }
}

output:

7
apple
lemon
orange
banana
litchi
mango
papaya

The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in an arbitrary order. This is using Java 6.

2
  • 8
    Just use a LinkedHashMap. Sep 30, 2015 at 14:19
  • @Raedwald Okay, but she did ask about insertion order multiple times, and it seems like LinkedHashMap is probably worth looking at. Nov 20, 2017 at 16:17

6 Answers 6

94

From the Javadoc: HashMap "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."

If you need consistent ordering, you can use LinkedHashMap (for insertion/access order), or TreeMap (for comparision order). Please note, that these maintain the order of the keys, not the values.

3
  • 3
    I think the OP was asking why the HashMap appears to preserving insertion order in his use-case. It is clear that he was expecting the iteration order to be more random.
    – Stephen C
    Nov 26, 2012 at 11:02
  • 1
    Although the ordering is for the keys, most of these maps actually store key/value entries (Map.Entry). Thus, values will most usually also appear in the same order as their associated keys. Aug 25, 2013 at 17:56
  • There is a difference between "we don't guarantee the order" and "we guarantee the order will look and/or actually be random". There's no reason for OP to expect that the data will look random.
    – ggorlen
    Sep 26, 2022 at 21:11
81

The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in random order.

The HashMap API does not define the order of iteration.

However, if you look at the implementation of HashMap, you can deduce that there is a complex transient relationship between the iteration order, the keys' hash values, the order in which the keys were inserted and the size of the hashtable. This relationship gets scrambled if the hashtable resizes itself.

In your case, you are using Integer keys which means that the hash values of the keys are the key values themselves. Also, you inserted the entries in key order. This leads (fortuitously!) to the iteration order matching the insertion order. But if you kept inserting more keys, you would find that the iteration order "wraps around". Then as the table goes through a series of resizes, the order will get progressively more and more scrambled.

In short, what you are seeing is an artefact of the hashtable implementation, and not something that you can (or should) sensibly make use of. Not least because it could change from one Java release to the next.

0
11

A LinkedHashMap is what you're after. From the doco, it differs from HashMap in that it maintains a doubly-linked list running through all of its entries

7

Try LinkedHashMap if order is important... see from JavaDoc

public class LinkedHashMap extends HashMap

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

1

A related collection is java.util.concurrent's ConcurrentSkipListMap. A skiplist allows you to traverse the entries in key order and also look them in random order (but not as fast as a HashMap).

There's a nice skiplist demo applet.

-1

No, the order is not preserved in case of HashMap (if you want sorted implementation.) In case you want keys to be sorted, you can use TreeMap.

for example - {[3=1],[2=50],[20=4],[14=1]} -> HashMap

for TreeMap, you get - {[2=50],[3=1],[14=1],[20=4]} -> TreeMap

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.