How to iterate through multiple HashMaps inside one HashMap
Hi,
Can some one please tell me how can I iterate through a HashMap that may contain some more HashMaps and they inturn may contain more HashMaps and so on. How can I iterate throught all the HashMaps recursively in order i.e. First HashMap finds a HashMap iterate through that and if that finds another HashMap them iterate through that first and so on.
Thanks
Demo:
import java.util.*;
public class MapOMatic extends HashMap < String, MapOMatic > {
private static final long serialVersionUID = 0;
public static void main(String[] args) {
MapOMatic map1 = new MapOMatic();
MapOMatic map2 = new MapOMatic();
MapOMatic map3 = new MapOMatic();
MapOMatic map4 = new MapOMatic();
map1.put("map2", map2);
map1.put("map3", map3);
map3.put("map4", map4);
dumpKeys(map1);
}
static void dumpKeys(MapOMatic map) {
if (!map.isEmpty()) {
System.out.println(map.keySet());
for(String key : map.keySet()) {
MapOMatic child = map.get(key);
if (child != null)
dumpKeys(child);
}
}
}
}
Hi,
Here is the sample scenario and the heirarchy can be deep x-number of levels:
HaspMap hm11 = new HashMap();
hm11.put("hm11","valuehm11");
hm11.put("hm111","valuehm111");
hm11.put("hm1111","valuehm1111");
HaspMap hm10 = new HashMap();
hm10.put("hm10","valuehm10");
hm10.put("hm100",hm11);
hm10.put("hm1000","valuehm1000");
HaspMap hm9 = new HashMap();
hm9.put("hm9",hm11);
hm9.put("hm99","valuehm99");
hm9.put("hm999",hm10);
HaspMap hm8 = new HashMap();
hm8.put("hm8","valuehm8");
hm8.put("hm88",hm9);
hm8.put("hm888","valuehm888");
HaspMap hm7 = new HashMap();
hm7.put("hm7","valuehm7");
hm7.put("hm77",hm8);
hm7.put("hm777","valuehm777");
HaspMap hm6 = new HashMap();
hm6.put("hm6",hm7);
hm6.put("hm66","valuehm66");
hm6.put("hm6666","valuehm666");
HaspMap hm1 = new HashMap();
hm1.put("hm1a",hm6);
hm1.put("hm11a",hm7);
hm1.put("hm111a","valuehm111");
hm1.put("hm1","valuehm1")
////
for (Iterator j = h.keySet ().iterator () ; j.hasNext () ; )
{
Object obj2 = (Object) j.next () ;
Object objValue2 = (Object) h.get (obj2) ;
if (objValue2 instanceof java.util.HashMap)
{
//wants to loop this HashMap now before the top one
}
else
{
;
}
}
///
Want to find out how to loop through this.
Thanks