I tried to iterate over hashmap in Java, which should be a fairly easy thing to do. However, the following code gives me some problems:
HashMap hm = new HashMap(
The cleanest way is to not (directly) use an iterator at all:
Like this:
Map hm = new HashMap();
hm.put(0, "zero");
hm.put(1, "one");
for (Map.Entry entry : hm.entrySet()) {
// do something with the entry
System.out.println(entry.getKey() + " - " + entry.getValue());
// the getters are typed:
Integer key = entry.getKey();
String value = entry.getValue();
}
This is way more efficient than iterating over keys, because you avoid n calls to get(key)
.