6

When we add values to hashmap<Key, Value> variable using put(), are they always ordering?

Because when I tried with simple codes they are ordering.

Example:

Map<Integer, Integer> ctrArMap = new HashMap<Integer, Integer>();
    ctrArMap.put( 1, 11);
    ctrArMap.put( 2, 12);
    ctrArMap.put( 3, 13);
    ctrArMap.put( 4, 14);
    ctrArMap.put( 5, 15);
    System.out.println(ctrArMap);

But in my case they aren't ordering.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Pally
  • 101
  • 1
  • 2
  • 8
  • see this http://stackoverflow.com/questions/2889777/difference-between-hashmap-linkedhashmap-and-treemap – Sachin Gupta Mar 16 '16 at 04:30
  • Yes, result are in order. I also wondering. I can say, its not true that HashMap has not inheriting order, we should say, HashMap may give insertion order in result but not always. – Ashu Phaugat Mar 16 '16 at 04:43

6 Answers6

18
  1. HashMap :- HashMap never preserves your Insertion Order. It Internally Use a hashing Concept by which it generate a HashCode to the Corresponding key and add it to the HashMap.

  2. LinkedHashMap :- LinkedHashMap It preserves your Insertion Order. and keys will be found as same order you Insert into this LinkedHashMap.

  3. TreeMap :- The TreeMap class implements the Map interface by using a Tree. A TreeMap provides an efficient means of storing key/value pairs in sorted order, and allows rapid retrieval.

You should note that, unlike a HashMap, a tree map guarantees that its elements will be sorted in ascending key order

Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52
6

HashMap has no inherent ordering. If you're looking for insertion order, use a LinkedHashMap. If you're looking for natural order (A-Z, 0-9), use a TreeMap.

Eric Guan
  • 15,474
  • 8
  • 50
  • 61
6

HashMap doesn't preserve the order of insertion. However if you use the values 0 to 10 in order, these happen to be hashed to the buckets 0 to 10 internally and placed in an array in that order. When you iterate of the HashMap you are looking at these buckets in order. Note: this implementation could change in the future and this might not happen.

The default size of a HashMap is 16 and with a load factor of 0.7 you can add 11 values without it resizing. This means when you view these values, the current implementation happens to place 0 to 10 in sorted order.

If you only need the values 0 to 10 be in order, I suggest using an array, instead of a HashMap.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
4

Use TreeMap for Ascending order.

Syntax:

TreeMap<Integer, Integer> ctrArMap= new TreeMap<Integer, Integer>();

    ctrArMap.put( 1, 11);
    ctrArMap.put( 3, 12);
    ctrArMap.put( 2, 13);
    ctrArMap.put( 5, 14);
    ctrArMap.put( 4, 15);
    System.out.println(ctrArMap);
Anand Kumar
  • 389
  • 1
  • 7
  • 21
1

The simple answer is no, a hash map doesn't have an "order". It is all determined based on how the object is hashed. For a number you could see some ordering, but that is purely based on the hashCode() method of the object that is the key for the put().

If you can get your hands on the source of the Integer class or similar number classes and look at the hashCode() method you'll probably see why your numbers in the HashMap come back in order. If you switch to a string key you will most likely immediately see that it is no longer sorted.

klog
  • 486
  • 3
  • 10
  • 1
    I am not 100% true, but I can say "Sometime HashMap gives the result in insertion order". Instead of saying 'Hashmap doesn't have an order', we should say, 'Hashmap sometime have an order but not always". Because if you run the above program it will give you result in order, so we can't avoid this. – Ashu Phaugat Mar 16 '16 at 05:13
  • 1
    I believe that if the order of insertion in the example was reversed, i.e., 5 4 3 2 1, you would still see an ascending order when printing. For a HashMap the order of the data is strictly tied to the hashed value of the key. – klog Mar 16 '16 at 05:23
0

There is another option from those listed here. map.entrySet().stream().reduce((one, two) -> two).get();

Notice that "HashMap" is replaced with "LinkedHashMap". HashMap re-orders your entries automatically, it's useful for example if your keys are integers and you want them in order. To preserve the insertion order (if that's what you want) you need a linked map. Experiment by changing from LinkedHashMap to HashMap and watch the order change.

final Map<String, Integer> map = new LinkedHashMap<>();
            map.put("test", 2);
            map.put("Not-Specified", 1);
            map.put("testtest", 3);
            map.put("another", 0);
            map.put("last", 5);


        Map.Entry<String,Integer> lastEntry = map.entrySet().stream().reduce((one, two) -> two).get();

        System.out.println("All entries : ");
        map.entrySet().stream().forEach(System.out::println);
        System.out.println("Last entry: " + lastEntry);