Search code examples
javahashmap

How to convert untyped Object to HashMap<String,Object>


I have Hashmap of <String, Object> that could contain different object type like String, Int. So I have already successfully cast the object to int and string. But When I try to cast it into a hashmap that doesn't work and I have empty value with no error.

Here is what I have try :

String str = "hey";
Int intVal= 66;
HashMap<String, String> myGetHashMapVal= new HashMap<>();

HashMap<String,Obj> objHashMap = new HashMap<>();

objHashMap.put("TheString",str);
objHashMap.put("TheInt",intVal);
objHashMap.put("HashMap",myGetHashMapVal);


HashMap<String, Object> hashMap = (HashMap<String, Object>) objHashMap.get("HashMap");

Solution

  • Well, this works just fine for me.

    HashMap<String,Object> map = new HashMap<>();
    map.put("myMap", map);
    map.put("int", 1);
    @SuppressWarnings("unchecked")
    HashMap<String,Object> map2 = (HashMap<String,Object>)map.get("myMap");
    System.out.println(map2.get("int"));
    

    Prints

    1