I have a hashmap
Map<String, Object> grpFields = new HashMap<String, Object>();
which is contained within another hashmap:
Map<Integer, Object> targetFields = new LinkedHashMap<Integer, Object>();
I can see it within debug mode:
20005=0, 453={452-2=7, 452-0=1, 452-1=17, 448-2=81, 448-1=0A, 447-2=D, 447-1=D, 447-0=D, 448-0=0A}, 11=1116744Pq2Q,
where 453 is the Hashmap, however when trying to extract the hashmap from the parent hashmap using:
HashMap <String, Object> grpMap453 = (HashMap)targetFields.get(453);
I'm thrown:
java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String
Surely the call targetFields.get(453);
should simply return a hashmap?
Flatten a Nested HashMapOne alternative to a nested HashMap is to use combined keys. A combined key usually concatenates the two keys from the nested structure with a dot in between. For example, the combined key would be Donut.
Nested HashMap is map inside another map. Its means if value of an HashMap is another HashMap.
A nested HashMap is Map inside a Map. The only difference between a HashMap and a nested HashMap is: For HashMap , the key or the value can be of any type (object). For Nested HashMap , the key can be of any type (object), but the value is another HashMap object only.
You can do it like you assumed. But your HashMap has to be templated: Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); Otherwise you have to do a cast to Map after you retrieve the second map from the first.
I've tried making a demo on the basis of what you have described and found no error in it.
HashMap<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("123", "xyz");
HashMap<Integer, Object> map = new HashMap<Integer, Object>();
map.put(453, hashMap);
HashMap<String, Object> newMap = (HashMap<String, Object>) map.get(453);
System.out.println("Main map "+ hashMap);
System.out.println("Map inside map "+map);
System.out.println("Extracted map "+newMap);
It gives warning at line HashMap<String, Object> newMap = (HashMap<String, Object>) map.get(453);
that is "Type safety: Unchecked cast from Object to HashMap" but no error at all.
Are you doing the same?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With