Skip to content
Advertisement

Not able to iterate arraylist which contains linked hashmap

I am trying to iterate over an instance of ArrayList of Object class using a for loop:

for(PayloadDTO payloadDTO:payloadDTOList) {
    if(payloadDTO.getEntType().equals(CommonConstants.CUSTOMENTTYPEROLEID.RES_ROLE_TYPE)) {
        resRoleNameList.add(payloadDTO.getEntName());
    } 
}

enter image description here

That gives me the following error:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.alnt.fabric.external.model.PayloadDTO
    at com.alnt.fabric.external.rbac.service.ExternalFabricService.loadImpactedUserCount(ExternalFabricService.java:384)
    at com.alnt.fabric.external.rbac.controller.ExternalFabricController.loadImpactedUserCount(ExternalFabricController.java:160)
    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)

So I tried to convert it using the code below:

payloadDTOList = convert(payloadDTOList.toString(), List<PayloadDTO.class>);


    public static <T> T convert(String json, Class<T> type) throws ALNTApplicationException {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(json, type);
    } catch (Exception e) {
        throw new ALNTApplicationException(FabricComponentErrorCodes.ACTION_HANDLER_ERROR_CODE,"Object conversion error");
    }
}

Advertisement

Answer

Try a for loop with casting

for (int i=0; i < payloadDTOList.size(); i++) {
    PayloadDTO payloadDTO = (PayloadDTO) payloadDTOList.get(i);       
    if(payloadDTO.getEntType().equals(CommonConstants.CUSTOMENTTYPEROLEID.RES_ROLE_TYPE)) {
      resRoleNameList.add(payloadDTO.getEntName());
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement