Posts Tagged ‘Iteration’

Inspecting HashMaps

November 7, 2010 Leave a comment

One query which seems to turn up frequently in the blog stat reports is how to iterate or print a HashMap so that its contents are visible. The bottom line is that HashMap itself doesn’t directly support an iterator. However the getKeys() method of HashMap returns a Set object which can be iterated without any problem.

public void printHashMap(HashMap ha)
Set keys = ha.keySet();
Iterator it = keys.iterator();

String sx = "";

while (it.hasNext()) {
          Object key =;
        String sKey = key.toString();
        Object val = ha.get(key);
        String kVal = val.toString();
        sx += sKey + " - " + kVal + "\n";



Obviously once you’ve got the trick of handing off the iteration of a HashMap to the Set returned by getKeys() life gets altogether more comfortable; no longer is that HashMap a ferociously daunting object lurking in memory,a monster which you can’t be certain at any time as to what it contains, but it becomes an altogether more amenable and house-trained creature.

I’ll get round to a few more of these over the coming weeks, in between writing some more semantic parsing code which I’ll also be blogging about.

Categories: Java Tags: , ,