Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the elements in correct order from iterator()

Here is my code to store the data into HashMap and display the data using iterator

public static void main(String args[]) {
    HashMap<String, String> hm = new HashMap<String, String>();
    hm.put("aaa", "111");
    hm.put("bbb", "222");
    hm.put("ccc", "333");
    hm.put("ddd", "444");
    hm.put("eee", "555");
    hm.put("fff", "666");

    Iterator iterator = hm.keySet().iterator();

    while (iterator.hasNext()) {
        String key = (String) iterator.next();
        String val = hm.get(key);

        System.out.println(key + " " + val);
    }
}

But it is not displaying in the order in which I stored. Could someone please tell me where am I going wrong? How can I get the elements in the order?

like image 923
Santhosh Avatar asked Aug 09 '11 12:08

Santhosh


2 Answers

A HashMap has no guaranteed order:

This class makes no guarantees as to the order of the map;

Use a LinkedHashMap.

Hash table and linked list implementation of the Map interface, with predictable iteration order.

like image 57
Jacob Avatar answered Sep 21 '22 08:09

Jacob


You need to use a LinkedHashMap because it maintains ordering of its entries, unlike HashMap.

From the javadocs:

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

like image 32
dogbane Avatar answered Sep 20 '22 08:09

dogbane