Iterate through a HashMap in Java

March 22, 2017

In Java, we can iterate through a HashMap in few different ways.

First of all, we need to import required packages:

Then, naturally, set our HashMap and put some data in there:

1. Values and Keys

The simplest way to iterate is using keys or values.

Using values:

If we use keys the important thing is that we can find the values using only them by using get(key).  Although it is a slow and not efficient method. In this example we print keys and values both in one line:


2. Using Entry

Another possibility is using entry

Thanks to this package we can use the set of keys and values to iterate by both of them. Nowe we can use *.getKey() and *.getValue().

3. Iterator

In Java, we can use Iterator object to iterate through elements. The same we can do here.

Now, using the while loop we can easily iterate through a HashMap

Click here to add a comment

Leave a comment: