I needed to iterate a HashMap in Java. I can do it effortlessly in PHP with just a regular array or in JavaScript with an object literal. In Java though, the process is a little bit more obtuse.
I had a special case – needing both the key and the value at the same time. Let’s go with one or the other for right now. Let’s establish our map.
HashMap<String, String> map = new HashMap<String, String>();
map.add("Hello", "world");
map.add("Ryan", "rampersad");
That’s our example map. It doesn’t really matter what the contents are, but it’s example.
Now, let’s loop over the keys.
Iterator it = map.keySet().iterator();
while (it.hasNext()) System.out.println( it.next() );
This will print out Hello and Ryan. Those are the keys of the values in the Hash Map.
Now let’s loop over the values.
Iterator it = map.values().iterator();
while (it.hasNext()) System.out.println( it.next() );
This will print out world and rampersad. Those are the values.
Finally, the most interesting. To get the value and the key at the same time, a special Map Entry object can be made with an entry set.
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> kv = it.next();
System.out.println(kv.getKey() + "=" + kv.getValue());
}
This code prints Hello=world and Ryan=rampersad.
This is new. First, we call entrySet to get the special set of key-value pairs. Then in the loop itself we use a special Map.Entry object with parameters of String, String, because that’s how our map is made, and set it to it.next. That enables use to call for the key and the value.
I hate while loops so I suggest this format instead.
for (Map.Entry<String, String> kv: map.entrySet()) {
System.out.println(kv.getKey() + "=" + kv.getValue());
}
The beauty of this is that there is no Map.Entry object being declared inside the actual loop, instead it’s made it its header. All the cleaner.
Getting a key-value pair from a HashMap, the point of HashMap, I think, is slightly convoluted but nothing hard.
Happy mapping.