Search code examples
javahashmap

Iterating over Map of Maps


I have a map of maps. I want to iterate over each entry and get the value out of it. Following is my code I am using, but I get an exception. I don't know what is wrong with my code.

for(Map.Entry<String, Object> entry : map.entrySet()){
    for (Map.Entry<String, Object> entry2 : ((Map<String, Object>)(Object) entry).entrySet()){
        sheet.addCell(new Label(c++, r+1, (String) entry2.getValue()));
    }

}

following is my stack trace:

java.lang.ClassCastException: java.util.HashMap$Node cannot be cast to java.util.Map
    at com.vz.stamps.services.TestServiceForOrderPopup.addExcelOutputHeader(TestServiceForOrderPopup.java:97)
    at com.vz.stamps.services.TestServiceForOrderPopup.createExcelOutputExcel(TestServiceForOrderPopup.java:56)
    at com.vz.stamps.controller.OrderviewOpenDriverController.downloadExcelOutputExl(OrderviewOpenDriverController.java:152)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)

Solution

  • You are getting error because after creating the EntrySet of first map and passing that for another iteration you are not calling getValue() on the EntrySet. So the code should be updated as:

    for(Map.Entry<String, Object> entry : map.entrySet()){
        for (Map.Entry<String, Object> entry2 : ((Map<String, Object>)(Object) entry.getValue()).entrySet()){
            sheet.addCell(new Label(c++, r+1, (String) entry2.getValue()));
        }
    
    }