Collections

Iterate through Java HashMap Example

This example shows how to iterate through Java HashMap and what is the best way among them.

How to iterate over Java HashMap?

We will use the example Employee class and store its objects into Java HashMap.

Let’s first store several Employee objects into the HashMap.

We have put employee ID as the key and employee object as the value for each mapping stored in the HashMap.

1) Iterate through keys of the HashMap

Use this approach if you are interested only in keys stored in the HashMap. Use keyset() method of the Java HashMap to get the Set view of the stored keys and for loop to iterate over them.

Output

2) Iterate through values of the HashMap

Use this approach if you are interested only in the values stored in the HashMap. Use values() method of the Java HashMap to get the Collection view of the stored values and for loop to iterate over them.

Output

3) Iterate through keys and values of the HashMap

Use this approach if you are interested in retrieving both keys and values stored in the HashMap. Use entrySet() method of the Java HashMap to get the Set view of stored mappings in form of Map.Entry object and use for loop to iterate over them.

Output

Important Note: If you are using Java version 1.4 or lower, for each loop will not work since it was introduced in Java 1.5. Also, Generics was introduced in Java version 1.5. Use following code to iterate through HashMap instead.

Using while loop:

Using for loop:

Please also note that, HashMap does not guarantee the order of elements returned. That means the returned values might not be in the same order in which they are inserted (you might see different output!)

Also See: How to iterate through List in Java

Please let us know your views in comments section.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

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