简体   繁体   中英

Adding an element into a HashMap in a HashMap

I have a HashMap which contains a HashMap as value. I would like to add a key-pair value into the HashMap considered as value. I wrote something like this

HashMap<String, HashMap<String, Integer>> record= new HashMap<>();
record.put("John",....)// I am not sure what to put here

How can that be done?

//get innerMap using key for record map
innerMap = record.get("John");
if(innerMap == null){ // do not create new innerMap everyTime, only when it is null
   innerMap = new HashMap<String, Integer>();
}
innerMap.put("Key", 6); // put using key for the second/inner map
record.put("John", innerMap)

So, That value has to be stored like this :

HashMap<String,Integer> value = new HashMap<>();
value.put("Your string",56);

Then add this value Hashmap into your record hashmap like this:

record.put("John",value);
HashMap<String, HashMap<String, Integer>> record= new HashMap<>();
HashMap hm = new HashMap<>();
hm.put("string", 1);
record.put("John", hm);

First you have to get an instance of HashMap

HashMap<String, Integer> map = new HashMap<>();
map.put("key", 1);

then

recore.put("John", map);

You can use like this -

 HashMap<String, HashMap<String, Integer>> record= new HashMap<String, HashMap<String, Integer>>();

    HashMap<String, Integer> subRecord = new HashMap<String, Integer>();
    subRecord.put("Maths", 90);
    subRecord.put("English", 85);

    record.put("John",subRecord);

I have seen many answers if you need information on how to fetch the values from the inner Hashmap Please refer this.

    HashMap<String, HashMap<String, Integer>> record= new HashMap<>();
    Map<String, Integer> innerMap = new HashMap<String, Integer>();    
    innerMap.put("InnerKey1", 1);
    innerMap.put("InnerKey2", 2);

Storing the value to outer Hashmap

   record.put("OuterKey", innerMap);

This is how you retrieve the values

  Map<String, Integer> map = record.get("OuterKey");
  Integer myValue1 = map.get("InnerKey1");
  Integer myValue2 = map.get("InnerKey2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM