How to loop through a Map in Java

In this post we will provide some examples of how to loop through a map in Java. You can do this in a few ways such as loop through keys, values or both.

How to loop through a Map in Java

Loop through Map with both keys and values (EntrySet)

The first example shows how to loop through the Map using an entrySet, which is a object containing both key and value of a map entry.

If you are using Java 8 you can use the forEach() method which is more concise.

If you require to delete some elements while you loop then you will need to use an iterator. Otherwise a ConcurrentModificationException will be thrown, if you use one of the examples above.

As you can see from the example above, iterator.remove() allows you to remove elements from the map whilst you are iterating through the map.

Running the above examples produces the following output:

Loop through Map keys

The next example shows how to loop through a map using the keys.

Running the above code produces the following:

Loop through Map values

Similar to looping through keys, the map object has a method called valueSet() which returns a set of values which we can iterate through.

Running the above code produces the following:

I hope this post has helped you understand how you can iterate through a map by going through the entrySet, keySet and valueSet.

Similar posts:

  1. How to convert a List to a Set
  2. Check if an array contains a certain value
  3. How to split a string in Java
  4. How to move a file in Java

References:

  1. Java 8 Map API Documentation

 

Leave a Reply