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.
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.
Nested Map is used in many cases, such as storing students' names with their Ids of different courses. In this case, we create a Map having a key, i.e., course name and value, i.e., another Map having a key, i.e., Id and value, i.e., the student's name. Take the total number of students from the user for each course.
We can compare two HashMap by comparing Entry with the equals() method of the Map returns true if the maps have the same key-value pairs that mean the same Entry.
Comparing Nested HashMaps We can compare them using the equals() method. The default implementation compares each value.
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.
Map map = new HashMap(); ((Map)map.get( "keyname" )).get( "nestedkeyname" );
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