user3841581
user3841581

Reputation: 2747

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?

Upvotes: 1

Views: 105

Answers (6)

RStack
RStack

Reputation: 230

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");

Upvotes: 0

Ravi
Ravi

Reputation: 31

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);

Upvotes: 2

vansi
vansi

Reputation: 21

First you have to get an instance of HashMap

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

then

recore.put("John", map);

Upvotes: 2

abhi_bond
abhi_bond

Reputation: 211

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);

Upvotes: 1

Ankit Deshpande
Ankit Deshpande

Reputation: 3604

//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)

Upvotes: 2

Jonatan
Jonatan

Reputation: 1242

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

Upvotes: 2

Related Questions