Different Ways to Iterate a HashMap in Java

In this post we’ll see different ways to iterate a Map or HashMap in Java. One thing you should know is you can’t directly loop a Map in Java (except when you use forEach statement). There are methods that return a “collection view” of the Map using that view you can iterate a HashMap in Java.

The methods that can be used for getting a “collection view” of the Map are as follows-

  • Set<Map.Entry<K,V>> entrySet()– Returns a Set view of the mappings contained in this map.
  • Set<K> keySet()– Returns a Set view of the keys contained in this map.
  • Collection<V> values()– Returns a Collection view of the values contained in this map.

Options for iterating a HashMap

As you can see from the above methods you either get a Set with Map.entry elements, a Set of keys of the maps or a Collection view of the Map values.

Using that view you can iterate using one of the following options-

  1. You can use For-Each loop (enhanced for loop), available from Java 5.
  2. You can iterate using Iterator. Using iterator() method you can get an iterator and then using the hashNext() and next() method of the iterator you can iterate a HashMap.
  3. You can also use forEach statement available from Java 8 to loop through Map.

Example code to iterate a HashMap in Java

Here is an example using all of the above mentioned methods for iterating a HashMap.

Using entrySet() method

Using entrySet() method you get the set view of the mappings stored in the HashMap in the form of Map.entry elements. Using that set view you can iterate a HashMap and get both key and value.


Using keySet() method

Using keySet() method you get the set view of the HashMap keys. Once you have the keys you can also get the values mapped to those keys using the get() method but that makes the looping of the Map slow in comparison to other ways.


Using values() method

If you just want to iterate over the values of the HashMap you can use the values() method.


Iterating a Map directly using forEach

As the saying goes “save the best for the last” here is a way to iterate a HashMap directly using forEach statement (Java 8 onwards).


That’s all for the topic Different Ways to Iterate a HashMap in Java. If something is missing or you have something to share about the topic please write a comment.

You may also like

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.