我有一个包含以下值的HashMap:
HashMap<String, JSONObject> myMap = new HashMap<String, JSONObject>();
JSONObject name1 = new JSONObject();
name1.put("name", "A");
..... //so on for name2 and name3
myMap.put("1", name1);
myMap.put("2", name2);
myMap.put("3", name3);
System.out.println(myMap.get("1");
Output is {"name", "A"}.
如何在现有键之一中插入附加值,以便输出应如下所示:
System.out.println(myMap.get("1");
=> Expected output is {{"name", "A"}, {"age", "30"}}
答案 0 :(得分:1)
您可以同时执行以下操作:
A)创建一个普通的HashMap
,其中值类型为容器(例如List
);
HashMap<String, List<Object>> myMultiMap = new HashMap<>();
// Add a list with the objects you want
myMultiMap.put("name", [a list with elements])
// You can use the .compute method to add elements to existing lists
或
B)创建一个多值映射,JDK默认未提供该多值映射,但是可以在Guava或Apache Commons之类的库中找到