Java Tips: Three Ways To Iterate Through A HashMap

freddywong

Joined January 2019

  • Artist
    Notes

Artist's Description

The HashMap is one of the most useful data structures in the Java programming language. Once you have a HashMap filled with data, you may want to iterate through its keys and values. Below are three different ways to iterate iphone app review through a Java HashMap.

Sample HashMap

Here is our sample HashMap. The key is an Integer and the value is a String. We first declare the HashMap. Then we add the values “zero”, “one” and “two” with the keys 0, 1 and 2 respectively.

HashMap hm = new HashMap();
hm.put(0, “zero”);
hm.put(1, “one”);
hm.put(2, “two”);

Now that the HashMap has data, we can iterate over the keys and values.

Iteration Example 1

In this example, we use a for each loop to iterate through the HashMap. We retrieve each entry and call methods to get the key and value.

for (Map.Entry entry : hm.entrySet()) {
System.out.print(“key,val: “);
System.out.println(entry.getKey() + “,” + entry.getValue());
}

Iteration Example 2

In this example, we use a while loop and an Iterator object. The keyset() method of the HashMap object gives us an Iterator object to iterate through all the keys. That Iterator object works well with loops. We retrieve each key by calling iter.next(). We can then use that key to retrieve the value from the HashMap.

Iterator iter = hm.keySet().iterator();
while(iter.hasNext()) {
Integer key = (Integer)iter.next();
String val = (String)hm.get(key);
System.out.println(“key,val: ” + key + “,” + val);
}

Iteration Example 3

In this final example, we use the Iterator of the entrySet() method of the HashMap object. The Iterator object and a loop allow us to easily retrieve the keys and values one by one. The it.next() method gives us the next entry in the HashMap. That entry lets us retrieve they key and value.

Iterator > it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entryentry=(Map.Entry) it.next();
Integer key = (Integer)entry.getKey();
String val = (String)entry.getValue();
System.out.println(“key,val: ” + key + “,” + val);
}

Output

No matter which of the above examples you try, the output will be as follows:

key,val: 0,zero
key,val: 1,one
key,val: 2,two

These are three different ways to iterate through an app HashMap. Feel free to try these examples yourself and use them in your own programs.

desktop tablet-landscape content-width tablet-portrait workstream-4-across phone-landscape phone-portrait
desktop tablet-landscape content-width tablet-portrait workstream-4-across phone-landscape phone-portrait