I have a HashMap in Java, the contents of which (as you all probably know) can be accessed by
HashMap.get("keyname");
If a have a HashMap inside another HashMap i.e. a nested HashMap, how would i access the contents? Can i do this like this, inline:
HashMap.get("keyname").get("nestedkeyname");
Thank you.
I prefer creating a custom map that extends HashMap. Then just override get() to add extra logic so that if the map doesnt contain your key. It will a create a new instance of the nested map, add it, then return it.
Now you can use it like so:
Yes.
See:
You can get the nested value by repeating
.get()
, but with deeply nested maps you have to do a lot of casting intoMap
. An easier way is to use a generic method for getting a nested value.Implementation
Usage
I hit this discussion while trying to figure out how to get a value from a nested map of unknown depth and it helped me come up with the following solution to my problem. It is overkill for the original question but maybe it will be helpful to someone that finds themselves in a situation where you have less knowledge about the map being searched.
Yes, if you use the proper generic type signature for the outer hashmap.
If you're not using generics, you'd have to do a cast to convert the object retrieved from the outer hash map to a
HashMap
(or at least aMap
) before you could call itsget()
method. But you should be using generics ;-)} }