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

Tags: , , , , , , ,

Trackback from your site.

Prithwiraj Bose

I am an Architect of Distributed Applications of Information Services Industries in TATA Consultancy Services Ltd. 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 are my favorite pass time. I've recently grown interest in Electronics, IoT and Robotics.

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.

    Reply

Leave a comment

%d bloggers like this: