How To Iterate Through A HashMap in Java

      1 Comment on How To Iterate Through A HashMap in Java
HashMap is one of the most useful collections in Java. It allows you to store Object against a key, which again can be any type of Object. Here I will show how to iterate through a HashMap, which is populated with number of objects.

Declare and populate a HashMap

HashMap<String, String> myMap = new HashMap<String, String>();
myMap.put("1","First Value");
myMap.put("2","Second Value");
myMap.put("3","Third Value");

I have shown 3 ways of iterating though a HashMap. In the code examples below, I’ll use the HashMap myMap, described above.

 
 

Iterating through HashMap : Way 1

for (Map.Entry entry : myMap.entrySet()) {
System.out.println("key=" + entry.getKey() + ", val=" + entry.getValue());
}

Iterating through HashMap : Way 3

Iterator it = myMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Integer key = (Integer)entry.getKey();
String val = (String)entry.getValue();
System.out.println("key=" + key + ", val=" + val);
}

Iterating through HashMap : Way 2

Iterator iter = myMap.keySet().iterator();
while(iter.hasNext()) {
Integer key = (Integer)iter.next();
String val = (String)myMap.get(key);
System.out.println("key=" + key + ", val=" + val);
}

All of the above examples will result as follows:

key=1, val=First Value
key=2, val=Second Value
key=3, val=Third Value
Please follow and like us:
Pin Share

1 comment on “How To Iterate Through A HashMap in Java

Leave a Reply

Your email address will not be published. Required fields are marked *