Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

storing hashMap in a hashMap

Tags:

i am reading data from a text file and want to store HashMap in another HashMap..

HashMap<string,HashMap<string,value>> 

how to store data and retrieve it? any sample code will be appreciated... thank u

like image 456
user625172 Avatar asked Feb 20 '11 11:02

user625172


People also ask

Can you put a HashMap into a HashMap?

Given a HashMap, there are three ways one can copy the given HashMap to another: By normally iterating and putting it to another HashMap using put(k, v) method. Using putAll() method. Using copy constructor.

What is HashMap can we store objects in HashMap and how do you retrieve them?

HashMap is similar to HashTable, but it is unsynchronized. It allows to store the null keys as well, but there should be only one null key object and there can be any number of null values. This class makes no guarantees as to the order of the map.

Can we have Map inside Map in Java?

In Java, Map is an interface that maps keys to values. Sometimes it is required to implement Map of Map (nested Map). Nested Map is used in many cases, such as storing students' names with their Ids of different courses.


2 Answers

Example:

Creating and populating the maps

Map<String, Map<String, Value>> outerMap = new HashMap<String, HashMap<String, Value>>(); Map<String, Value> innerMap = new HashMap<String, Value>();     innerMap.put("innerKey", new Value()); 

Storing a map

outerMap.put("key", innerMap); 

Retrieving a map and its values

Map<String, Value> map = outerMap.get("key"); Value value = map.get("innerKey"); 
like image 117
Johan Sjöberg Avatar answered Sep 28 '22 11:09

Johan Sjöberg


Creating two Simple Hashmaps: InnerMap and OuterMap

    HashMap<String, HashMap<String, String>> outerMap = new HashMap<String, HashMap<String,String>>();     HashMap<String, String> innerMap = new HashMap<String, String>(); 

Populating the HashMaps

    innerMap.put("InnerKey", "InnerValue");     outerMap.put("OuterKey", innerMap); 

Retreiving values from HashMaps

    String value = ((HashMap<String, String>)outerMap.get("OuterKey")).get("InnerKey").toString();     System.out.println("Retreived value is : " + value); 
like image 27
AnshulGarg Avatar answered Sep 28 '22 12:09

AnshulGarg