-1

We observed below mentioned program which uses hash map still gives the output in ascending order of the keys.

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

public class SampleProgram {
    public static void main(String[] args) {
        HashMap<Integer, String> hmap = new HashMap<Integer, String>();
        hmap.put(100, "A");
        hmap.put(107, "C");
        hmap.put(101, "Z");
        hmap.put(106, "Y");
        hmap.put(104, "P");
        hmap.put(105, "Q");
        hmap.put(108, "R");
        Set set = hmap.entrySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry me = (Map.Entry) iterator.next();
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
    }
}

As i read in java documents, that hash map does not return any order. But we observed that in the above mentioned program it is sorting the keys and returning the output.But at the same time we used following data set to cross verify that time it is not sorting.So, what is the reason ?

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class SampleProgram {
public static void main(String[] args) {
        HashMap<Integer, String> hmap = new HashMap<Integer, String>();
        hmap.put(30, "A");
        hmap.put(5, "C");
        hmap.put(76, "Z");
        hmap.put(100, "Y");
        hmap.put(90, "P");
        hmap.put(34, "Q");
        hmap.put(23, "R");
        Set set = hmap.entrySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            Map.Entry me = (Map.Entry) iterator.next();
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
    }
}
Jeevan
  • 1
  • 1
  • 4
    Is there a question here? – Eran Feb 01 '18 at 10:49
  • 3
    The order of iteration is undefined - that means it can be ascending, descending or anything else. What is the question exactly? – Boris the Spider Feb 01 '18 at 10:52
  • Welcome to Stack Overflow! Please take the [tour](/tour), have a look around, and read through the [help center](/help), in particular [How do I ask a good question?](/help/how-to-ask) and [What topics can I ask about here?](/help/on-topic). – Timothy Truckle Feb 01 '18 at 10:52
  • Also - **DON'T USE RAWTYPES**. – Boris the Spider Feb 01 '18 at 10:52
  • 2
    This could be a duplicate of [Why is HashSet maintaining natural/ alphabetical order?](https://stackoverflow.com/questions/48560736/why-is-hashset-maintaining-natural-alphabetical-order). Although this question is about a HashMap instead of HashSet the explanation is basicly the same: Your keys are a very small subset and this case is an exception. Try adding some more keys with different ranges `hmap.put(100001, "FART");hmap.put(1000, "BURP");` and watch your ascending order crumble. – OH GOD SPIDERS Feb 01 '18 at 11:02
  • 1
    Possible duplicate of [Why is HashSet maintaining natural/ alphabetical order?](https://stackoverflow.com/questions/48560736/why-is-hashset-maintaining-natural-alphabetical-order) – Ole V.V. Feb 01 '18 at 11:42
  • HashMap doesn't have any particular ordering, use LinkedHashMap if you need it. – Konrad Borowski Feb 02 '18 at 10:18
  • The OP is not asking how to implement and ordered map. He is asking why a map that should not be ordered appears to be ordered. – rghome Feb 02 '18 at 11:04

2 Answers2

1

If you want to maintain the order of entries, you should use LinkedHashMap instead. From Javadoc:

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

To understand why in your particular case entrySet seems to "sort" entries, let's look how hash table data structure works.

So there is array of buckets, with initial size of 16 (in case of HashMap implementation). The bucket's index of entry is determined by simple formulae: key_hash_code % buckets_array_size.

Let's look at your example and find in which buckets entries are put.

First code snippet:

Integer.hashCode(100) % 16 = 4
Integer.hashCode(107) % 16 = 11
Integer.hashCode(101) % 16 = 5
Integer.hashCode(106) % 16 = 10
Integer.hashCode(104) % 16 = 8
Integer.hashCode(105) % 16 = 9
Integer.hashCode(108) % 16 = 12

Second code snippet:

Integer.hashCode(30) % 16 = 14
Integer.hashCode(5) % 16 = 5
Integer.hashCode(76) % 16 = 12
Integer.hashCode(100) % 16 = 4
Integer.hashCode(90) % 16 = 10
Integer.hashCode(34) % 16 = 2
Integer.hashCode(23) % 16 = 7

So that's clearly explains why entries are printed in ordered manner in your first code snippet, and not in the second.

alxg2112
  • 308
  • 2
  • 11
  • As i read in java documents, that hash map does not return any order. But we observed that in the above mentioned program it is sorting the keys and returning the output.But at the same time we used following data set to cross verify that time it is not sorting.So, what is the reason ? – Jeevan Feb 02 '18 at 06:26
  • hmap.put(100, "A"); hmap.put(5, "C"); hmap.put(70, "Z"); hmap.put(20, "Y"); hmap.put(80, "P"); hmap.put(44, "Q"); hmap.put(76, "R"); – Jeevan Feb 02 '18 at 06:30
  • @Jeevan Please take a look at updated answer and let me know if you need some further explanation – alxg2112 Feb 02 '18 at 09:31
0

The entrySet() method you used for the iteration returns a Set view of the mappings inside the map.

Sets and HashMaps have no guarantees as to the order. In particular, it does not guarantee that the order will remain constant over time.

If you want the elements of your HashMap sorted you can use the following steps:

Set hmap = new HashSet();

...

List sortedList = new ArrayList(hmap);
Collections.sort(sortedList);
Borian
  • 622
  • 10
  • 19