Recursively Iterate HashMaps with Java

On March 29, 2013, in Java, Programming, by LuCuS

Recursively iterate HashMaps using Java.

private static void iterateHashMap(HashMap<String, Object> map)
{
	Iterator it = map.keySet().iterator();
	while (it.hasNext())
	{
		String key = (String)it.next();
		System.out.println(key + " = " + map.get(key));
		if (map.get(key) instanceof HashMap)
			iterateHashMap((HashMap)map.get(key));
	}
}

And to test it…

public void main(String[] args)
{
	HashMap<String, Object> map = new HashMap<String, Object>();
	map.put("Hello", "World");
	
	HashMap<String, Object> map2 = new HashMap<String, Object>();
	map2.put("Goodbye", "World");
	
	map.put("Map2", map2);
	
	iterateHashMap(map);
}

Output

Map2 = {Goodbye=World}
Goodbye = World
Hello = World

Thank you for your interest in my site. If you find the information provided on this site useful, please consider making a donation to help continue development!

PayPal will open in a new tab.
$2.00
$5.00
Other

Related Posts

Tagged with:  

Leave a Reply