How To Iterate Through A HashMap in Java

Written by Prithwiraj Bose on . Posted in Programming Tips Tricks Tutorials

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

Tags: , , , , , , ,

Trackback from your site.

Prithwiraj Bose

I am working as an I.T. Analyst in TATA Consultancy Services. I live in Kolkata, India. I love computers, programming, travelling and singing. Photography, spending time with my aquarium, designing a random website, painting, and singing is my favorite pass time.

Comments (1)

  • Mary Loucaskey


    This is my first time pay a visit at here and i am actually impressed to read all
    at single place.


Leave a comment