循环遍历hashmap以将相同键的值分组为<key,list <values =“”>&gt;对</键,>

时间:2013-02-27 15:34:20

标签: java hashmap

我一直在努力想出一种创建HashMap的方法,该方法将具有相同键的值(列表)分组。这就是我的意思:

说我有以下键和值:

Value     Key  *Sorry I got the columns swapped
1         10 
1         11 
1         12 
2         20 
3         30 
3         31 

我想将这些值放入

Hashmap <Integer, List<Integer>>

这样它就会将值组合到具有相同键的List Integer中,如下所示:

(1,{10,11,12}),(2,{20}),(3,{30,31})

现在,密钥和值存储在

Hashmap <Integer, Integer>

我迷失在如何遍历此Hashmap以使用键创建新的Hashmap:值列表对。有没有人对这个话题有好的方法?

4 个答案:

答案 0 :(得分:9)

假设您创建了HashMap<Integer, List<Integer>>,并且想要按照您的要求添加键值对,则可以使用以下方法:

public void addToMap(HashMap<Integer, List<Integer>> map, Integer key, Integer value){
  if(!map.containsKey(key)){
    map.put(key, new ArrayList<>());
  }
  map.get(key).add(value);
}

将此方法与示例数据一起使用:

HashMap<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
addToMap(map, 1, 10); 
addToMap(map, 1, 11);
addToMap(map, 2, 20);
addToMap(map, 3, 30);
addToMap(map, 3, 31);

答案 1 :(得分:8)

而不是普通Map使用Google Guava的Multimap

Multimap

  

...将键映射到值的集合,类似于Map,但每个键可以与多个值相关联。

这个概念当然也在其他图书馆中实现,Guava只是我个人的偏好。

答案 2 :(得分:1)

HashMap只为每个Integer存储1个值。因此迭代它应该只给出以下值:

Key      Value 
1         12 
2         20 
3         31 

要迭代Map的内容,您可以使用 entrySet()方法:

for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}

要构建List of Map,我建议这样做:

List<Integer> list = map.get(key);
if(list == null) {
    list = new ArrayList<Integer>();
    map.put(key, list);
}
list.add(value);

答案 3 :(得分:0)

您的实际情况不起作用,因为HashMap<Integer,Integer>无法存储两对与1,101,11相同的密钥对。

您可以轻松开发自己的多图,但最好的办法是使用已为此开发的类,Apache Commons框架已经为您准备了MultiValueMap<K,V>类。