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?
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.
//similarly you can use iterator to access data too.It will display dfata in order in which you added to it.
A HashMap has no guaranteed order:
Use a LinkedHashMap.
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.
You need to use a LinkedHashMap because it maintains ordering of its entries, unlike HashMap.
From the javadocs: