susparsy
susparsy

Reputation: 1046

Iterate through hashmap

Something very wiered.

This is my code:

Map<String, Object[]> data = new HashMap<String, Object[]>();
    data.put("1", new Object[] {"VENDOR_NAME", "COUNTRY_CODE", "PREFIX" , "RATE" , "CURRENCY" });
    data.put("2", new Object[] {10d, "John", 1500000d});
    data.put("3", new Object[] {2d, "Sam", 800000d});
    data.put("4", new Object[] {3d, "Dean", 700000d});

    Set<String> keyset = data.keySet();
    int rownum = 0;
    for (String key : keyset) {
        System.out.println(key);
    }

The result: 3 , 2 ,1 ,4

Why is the order all mixed :S ?

Upvotes: 0

Views: 458

Answers (2)

Rahul
Rahul

Reputation: 45080

If you have a look at the docs:-

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) 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.

That's why you're seeing the order getting all mixed up. As @Rohit suggested, try using a LinkedHashMap if you want to maintain the order.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213391

Why is the order all mixed :S ?

Because a HashMap doesn't guarantee any order of iteration of it's element. You will not get any constant order. If you want the insertion order, use a LinkedHashMap.

Upvotes: 2

Related Questions