Reputation: 75
Below is my code.Any help is appreciated.
I am simply not able to read list and create a Map.
I am passing a List<Map<String, Object>>
as a
function parameter till the Rest layer.In Rest Proxy call its a
plain List. In my service layer I need to use Map values stored in the List.
My List has values as mentioned
[{ID=56, VALUE=CPR,DESCRIPTOR=HEAD},
{ID=68,VALUE=RegFinance,DESCRIPTOR=FINANCE}]
I want a create Map<String,Map> using List<Map<String, Object>>
in below format
{56={ID=56, VALUE=CPR,DESCRIPTOR=HEAD},
68={ID=68,VALUE=RegFinance,DESCRIPTOR=FINANCE}}
Below code works before rest call is made i.e in Controller layer but does not work in Service layer after rest call.
Map<String, Object> userRoleMap = new HashMap<>();
for (int count = 0; count < allRolesDetails.size(); count++) {
//Map<String, Object> mapp=allRolesDetails.get(count);
//Above line Gives Exception
String[] singleColumn = allRolesDetails.get(count).toString().split(",");
//Above line Gives Exception
for(String pair : singleColumn)
{
String[] entry = pair.split("=");
userRoleMap.put(entry[1].trim(),allRolesDetails.get(count));
break;//add them to the hashmap and trim whitespaces
}
}
Tried all other options on StackoverFlow
Iterator<Map<String, Object>> it = allRolesDetails.iterator();
while (it.hasNext()) {
Map<String, Object> map = it.next(); //so here you don't need a potentially unsafe cast
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
And
for(Map<String, Object> map:allRolesDetails){
for(Map.Entry<String, Object>entry : map.entrySet()){
String Key=entry.getKey();
Object Value=entry.getValue();
}
}
In all the cases I am getting the below exception whenever I am using allRolesDetails.get(count)
or trying to user Iterator or Map.Entry.
java.lang.ClassCastException: java.lang.String cannot be cast to java.util.Map
Upvotes: 0
Views: 1666
Reputation: 75
I found out the solution. As I mentioned
Below code works before rest call is made i.e in Controller layer but does not work in Service layer after rest call.
There was an Issue with type of parameter I was passing in RestProxy Call
I was passing @QueryParam(value = "allRolesDetails") List allRolesDetails
instead of final List<Map<String, Object>> allRolesDetails
.After this change proper Map was getting retrieved while iterating List.
This post helped me find my problem.
sending List/Map as POST parameter jersey
Upvotes: 0
Reputation: 12463
You are typing a LOT of code here, when you could just do this
Map<String, Map<String, Object>> userRoleMap = new HashMap<>();
for (Map<String, Object> m : allRolesDetails) {
userRoleMap.put(m.get("ID"), m);
}
Upvotes: 1