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.
As others have said you can do this but you should define the map with generics like so:
However, if you just blindly run the following:
you will get a null pointer exception whenever keyname is not in the map and your program will crash. You really should add the following check:
I came to this StackOverflow page looking for a something ala
valueForKeyPath
known from objc. I also came by another post - "Key-Value Coding" for Java, but ended up writing my own.I'm still looking for at better solution than
PropertyUtils.getProperty
in apache'sbeanutils
library.Usage
Implementation
You can do it like you assumed. But your HashMap has to be templated:
Otherwise you have to do a cast to
Map
after you retrieve the second map from the first.If you plan on constructing HashMaps with variable depth, use a recursive data structure.
Below is an implementation providing a sample interface:
and example usage: