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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With