从 hashmap 存储和检索 ArrayList 值

新手上路,请多包涵

我有以下类型的哈希图

HashMap<String,ArrayList<Integer>> map=new HashMap<String,ArrayList<Integer>>();

存储的值是这样的:

 mango | 0,4,8,9,12
apple | 2,3
grapes| 1,7
peach | 5,6,11

我想使用迭代器或任何其他方式以最少的代码行存储和获取这些整数。我该怎么做?

编辑 1

这些数字是随机添加的(不是一起添加的),因为密钥与相应的行匹配。

编辑 2

添加时如何指向数组列表?

在 --- 行中添加新号码 18map.put(string,number);

原文由 Naveen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 399
1 个回答

我们的变量:

 Map<String, List<Integer>> map = new HashMap<String, List<Integer>>();

储藏:

 map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));

要将数字一和一相加,您可以这样做:

 String key = "mango";
int number = 42;
if (map.get(key) == null) {
    map.put(key, new ArrayList<Integer>());
}
map.get(key).add(number);

在 Java 8 中,如果列表不存在,您可以使用 putIfAbsent 添加列表:

 map.putIfAbsent(key, new ArrayList<Integer>());
map.get(key).add(number);


使用 map.entrySet() 方法迭代:

 for (Entry<String, List<Integer>> ee : map.entrySet()) {
    String key = ee.getKey();
    List<Integer> values = ee.getValue();
    // TODO: Do something.
}

原文由 Simon Forsberg 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题