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 through a Java HashMap.
Sample HashMapHere is our sample HashMap. The key is an Integer and the value is a String:
HashMap <Integer, String> hm = new HashMap<Integer, String>();
hm.put(0, "zero");
hm.put(1, "one");
hm.put(2, "two");
In the above Java code, we first declare the HashMap. Then we add the values "zero", "one" and "two" with the keys 0, 1 and 2 respectively. Now that the HashMap has data, we can try to iterate over the keys and values.
Iteration Example 1for (int i=0; i < hm.size(); i++) {
Integer key = hm.keySet().toArray()[i];
String val = hm.values().toArray()[i];
System.out.println("key,val: " + key + "," + val);
}In this example, we use a
for loop to iterate through the HashMap. We retrieve each key by calling the keyset() method of the HashMap, getting an array version of it and accessing it with the loop counter. Similarly, we retrieve each value by calling the values() method of the HashMap.
Iteration Example 2Iterator iter = hm.keySet().iterator();
while(iter.hasNext()) {
Integer key = iter.next();
String val = hm.get(key);
System.out.println("key,val: " + key + "," + val);
}
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.
Iteration Example 3Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Integer key = entry.getKey();
String val = entry.getValue();
System.out.println("key,val: " + key + "," + val);
}
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 to retrieve they key and value.
OutputNo matter which of the above examples you try, the output will be as follows:
Output:
key,val: 0,zero
key,val: 1,one
key,val: 2,two
Those are three different ways to iterate through a HashMap. Feel free to try these examples yourself and use them in your own programs.