Jagannath Sabat
Jagannath Sabat

Reputation: 118

When I print map data I always get in sorted order why?

This is the code i am trying to print map.

package beginnersbook.list.map;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

public class MapExample1 {

    public static void main(String[] args) {

        HashMap<Integer, String> hashMap = new HashMap<Integer, String>();

        hashMap.put(2, "Jagannath");
        hashMap.put(1, "Somonath");
        hashMap.put(3, "Kedarnath");

        Set<Entry<Integer, String>> set = hashMap.entrySet();

        Iterator<Entry<Integer, String>> iterator = set.iterator();

        //Using while loop
        System.out.println("Using while loop");
        while(iterator.hasNext()){
            Entry<Integer, String> mEntry = (Entry<Integer, String>) iterator.next(); 
            System.out.println("Key : "+mEntry.getKey()+" - Value : "+mEntry.getValue());
        }

        //for loop
        System.out.println("Using Advanced for loop");

        for(Entry<Integer, String> entry : hashMap.entrySet()){
            System.out.println("Key : "+entry.getKey()+" - Value : "+entry.getValue());
        }

    }

 }

This is my code. I think when a map is printed it prints in a varied order each time, however I am getting always the content in a sorted order.

Upvotes: 0

Views: 133

Answers (2)

yshavit
yshavit

Reputation: 43391

There is a big difference between "unspecified" and "random." HashMap's order is unspecified, but not random.

If you enter the same keys into a HashMap, in the same order, then you'll get the same result each time. This is (very) roughly analogous to how if you start with the same seed, a pseudorandom number generator will generate the same sequence each time.

In this case, as Colonel Thirty Two pointed out in the comments, the order happened to be the same as the keys' natural ordering. With three key-value pairs, there are 6 possible orderings (the permutations of the set {1, 2, 3}), so there's about a 17% chance that you'd see this happen -- not too unlikely at all.

What the "unspecified" means is essentially, "we can do whatever we want." It gives the implementers freedom to perform whatever hashing algorithm they want, resolve conflicts in whatever way is convenient, resize the HashMap's buckets without regard to maintaining order, etc. If they wanted to, they could explicitly add randomization and still be within the specs; but they didn't, because there's no need. So the code itself is deterministic, which means given the same inputs (for instance, a list of key-value pairs to be inserted) it will always produce the same output (a map whose toString looks the same each time).

Upvotes: 1

Siva Kumar
Siva Kumar

Reputation: 2006

HashMap is internally using Hashing algorithm.

It doesnt maintain order.

If you want to maintain order of the insertion Use LinkedHashMap

Upvotes: 1

Related Questions