开发者

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 = 开发者_如何学Chm.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?


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.


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


HashMap does not keep order in which we put data into it.So You may follow LinkedHashMap instead.It keeps the order in which we put data.LinkedHashMap can be used same as HashMap.

Map<key,value> map=new LinkedHashMap<key,value>();
map.put("key","value");
map.put("key","value");
map.put("key","value");

//similarly you can use iterator to access data too.It will display dfata in order in which you added to it.


The reason is HashMap and HashSet doesn't guarantee the order of the stored values. Position of the elements will depends on the size of the internal table and hashCode of the key.

If you want to load your data in some order you need to sort keys/or values. For example you can put collections of the entries (Map.entrySet()) to the list and sort by any criteria you want. Or you can use SortedMap (TreeMap for example) to store your objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜