存储和检索HashMap的ArrayList中值 [英] Storing and Retrieving ArrayList values from hashmap
问题描述
我有以下类型的一个HashMap
I have a hashmap of the following type
HashMap<String,ArrayList<Integer>> map=new HashMap<String,ArrayList<Integer>>();
存储的值是这样的:
The values stored are like this :
mango | 0,4,8,9,12
apple | 2,3
grapes| 1,7
peach | 5,6,11
我要存储以及使用迭代器或与$最低线C $ c.How我可以做任何其他方式获取这些整数?
I want to store as well as fetch those Integers using Iterator or any other way with minimum lines of code.How can I do it?
修改1
中的数字是随机(不在一起)的关键是匹配到合适的行补充说。
The numbers are added at random (not together) as key is matched to the appropriate line.
编辑2
我怎么可以指向到ArrayList同时加入?
How can I point to the arraylist while adding ?
我收到错误,同时增加一个新的号码 18
在该行 map.put(字符串,数字);
I am getting error while adding a new number 18
in the line map.put(string,number);
推荐答案
要保存:
map.put("mango", new ArrayList<Integer>(Arrays.asList(0, 4, 8, 9, 12)));
要添加数字一加一,你可以做这样的事情:
To add numbers one and one, you can do something like this:
String key = "mango";
int number = 42;
if (map.get(key) == null) map.put(key, new ArrayList<Integer>());
map.get(key).add(number);
使用 map.entrySet()
方法循环的:
for (Entry<String, ArrayList<Integer>> ee : map.entrySet()) {
String key = ee.getKey();
ArrayList<Integer> values = ee.getValue();
// TODO: Do something.
}
这篇关于存储和检索HashMap的ArrayList中值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!