Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access nested HashMaps in Java?

Tags:

java

hashmap

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.

like image 567
Mridang Agarwalla Avatar asked May 05 '10 15:05

Mridang Agarwalla


People also ask

How do I access nested HashMap?

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.

How do I use a nested map?

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.

Can we compare two HashMaps in Java?

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.

How does nested HashMap compare to Java?

Comparing Nested HashMaps We can compare them using the equals() method. The default implementation compares each value.


1 Answers

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" ); 
like image 180
tangens Avatar answered Sep 22 '22 05:09

tangens