我有一个包含HashMap作为值的HashMap。我想将一个密钥对值添加到被视为值的HashMap中。我写了这样的东西
HashMap<String, HashMap<String, Integer>> record= new HashMap<>();
record.put("John",....)// I am not sure what to put here
怎么办呢?
答案 0 :(得分:2)
//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)
答案 1 :(得分:2)
所以,那个值必须像这样存储:
HashMap<String,Integer> value = new HashMap<>();
value.put("Your string",56);
然后将此值Hashmap添加到您的记录哈希映射中,如下所示:
record.put("John",value);
答案 2 :(得分:2)
HashMap<String, HashMap<String, Integer>> record= new HashMap<>();
HashMap hm = new HashMap<>();
hm.put("string", 1);
record.put("John", hm);
答案 3 :(得分:1)
首先,您必须获取HashMap的实例
HashMap<String, Integer> map = new HashMap<>();
map.put("key", 1);
然后
recore.put("John", map);
答案 4 :(得分:1)
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);
答案 5 :(得分:0)
如果您需要有关如何从内部Hashmap获取值的信息,我已经看到了很多答案。请参阅此内容。
HashMap<String, HashMap<String, Integer>> record= new HashMap<>();
Map<String, Integer> innerMap = new HashMap<String, Integer>();
innerMap.put("InnerKey1", 1);
innerMap.put("InnerKey2", 2);
将值存储到外部Hashmap
record.put("OuterKey", innerMap);
这是检索值的方法
Map<String, Integer> map = record.get("OuterKey");
Integer myValue1 = map.get("InnerKey1");
Integer myValue2 = map.get("InnerKey2");