Michael
Michael

Reputation: 1251

Java HashMap<String, String> has LinkedHashMap in value

So I have a strange issue with a HashMap and not sure how to access the value. I have a HashMap returned to me from an API that is suppose to be HashMap<String, String>. One of the values is actually a LinkedHashMap. I've tried casting it, but since it is a HashMap that is <String, String> it's giving me an error that it's not possible. Is there anyway to get a LinkedHashMap value out of a HashMap that is <String, String>?

I have tried this with no luck: ((HashMap)userInfo.get("key")).get("key");

     Could not complete request <java.lang.ClassCastException: 
java.util.LinkedHashMap cannot be cast to java.lang.String>java.lang.ClassCastException:

java.util.LinkedHashMap cannot be cast to java.lang.String

This is really ugly looking, but I was actually able to get it out of the HashMap with this:

(HashMap) ((HashMap)((HashMap)userInfo).get("picture")).get("data");

Thanks to Jeroen for sending me down the right path.

Upvotes: 0

Views: 5183

Answers (3)

Juha Syrj&#228;l&#228;
Juha Syrj&#228;l&#228;

Reputation: 34271

Convert typed map first to untyped map and then check type of each value. Map interface is implemented by HashMap and LinkedHashMap classes so you'll most likely want to use it instead of more specific types.

HashMap<String, String> typedMap = ...
Map untypedMap = (Map) typedMap;
Object mapValue = untypedMap.get("key");

if(mapValue instanceof Map) {
  // handle as Map
}

if(mapValue instanceof String) {
  // handle as String
}

Upvotes: 1

OldCurmudgeon
OldCurmudgeon

Reputation: 65811

If it is a LinkedHashMap and you cast it to a HashMap you will have probelms.

You could instead treat it as a Map:

Map m = userInfo.get("key");

Upvotes: 0

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

Brackets placement.

Try

(((HashMap)userInfo).get("key")).get("key");

You have to cast before you use .get() (assuming your attempt is actually valid and it is just a matter of brackets).

Upvotes: 1

Related Questions