Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception java.util.LinkedHashMap cannot be cast to java.util.List

While working around following code I got the exception given below.

List<Map<String, Object>> obj = mapper.readValue(result.getBody(), new TypeReference<Map<String,Object>>(){});

for (Map<String, Object> map : obj) {
    for(Map.Entry<String, Object> entry : map.entrySet()){
        System.out.println("Key : "+entry.getKey()+" Value is: "+entry.getValue());
    }
}

Stacktrace: java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to java.util.List

like image 349
Vamsi Avatar asked Feb 23 '16 07:02

Vamsi


People also ask

How do I resolve Java Lang ClassCastException error?

How to handle ClassCastException. To prevent the ClassCastException exception, one should be careful when casting objects to a specific class or interface and ensure that the target type is a child of the source type, and that the actual object is an instance of that type.

What is LinkedHashMap in Java?

The LinkedHashMap class of the Java collections framework provides the hash table and linked list implementation of the Map interface. The LinkedHashMap interface extends the HashMap class to store its entries in a hash table. It internally maintains a doubly-linked list among all of its entries to order its entries.

How get values from LinkedHashMap?

You can convert all the keys of LinkedHashMap to a set using Keyset method and then convert the set to an array by using toArray method now using array index access the key and get the value from LinkedHashMap.

What is the difference between HashMap and LinkedHashMap in Java?

The Major Difference between the HashMap and LinkedHashMap is the ordering of the elements. The LinkedHashMap provides a way to order and trace the elements. Comparatively, the HashMap does not support the ordering of the elements.


2 Answers

You need to use only a Map instead of List of Map.

 Map<String, Object> object = mapper.readValue(result.getBody(), new TypeReference<Map<String,Object>>(){});
 for(Map.Entry<String, Object> entry : object.entrySet()){
    System.out.println("Key : "+entry.getKey()+" Value is:"+entry.getValue());
}
like image 124
Lilia Avatar answered Nov 02 '22 13:11

Lilia


Try This : Are you trying to Store MapObject in List.so instead of Map store in List.

instead of:

List<Map<String, Object>> obj = mapper.readValue(result.getBody(),
new TypeReference<Map<String,Object>>(){});

Use This :

List<Map<String, Object>> obj = mapper.readValue(result.getBody(), 
new TypeReference<List<Map<String,Object>>>(){});

For Demo example This Link

like image 43
Benjamin Avatar answered Nov 02 '22 14:11

Benjamin