【问题标题】:Looping through hashmap to group the values of same key into a <key, list<values>> pair通过 hashmap 循环将相同键的值分组为 <key, list<values>> 对
【发布时间】:2013-02-13 11:46:02
【问题描述】:

我一直很难想出一种方法来创建一个 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:值对列表。有没有人对这个话题有好的方法?

【问题讨论】:

  • 您确定这些值存储在Map 中吗?
  • 由于HashMap 中的密钥是唯一的,我敢打赌您的大部分信息都丢失了。执行一个简单的for (Map.Entry&lt;Integer, Integer&gt; e : yourMap) { out.println(e.getKey() + " " + e.getValue()); } 循环来检查当前地图的内容。
  • 地图有唯一的键。键1是怎么重复的?
  • Hashmap 不允许一个键有多个值 - 您不能在 HashMap, period 中发布初始列表。
  • 我做了out.print,键和值都按原样打印出来了

标签: java hashmap


【解决方案1】:

假设您创建了一个HashMap&lt;Integer, List&lt;Integer&gt;&gt;,并且您想按照您要求的方式为其添加一个键值对,您可以使用以下方法:

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);

【讨论】:

  • map.contains(key) 或 map.containsKey(key)
【解决方案2】:

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

Multimap 是一个

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

这个概念当然已经在其他库中实现了,Guava 只是我个人的喜好。

【讨论】:

    【解决方案3】:

    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<Integer> list = map.get(key);
    if(list == null) {
        list = new ArrayList<Integer>();
        map.put(key, list);
    }
    list.add(value);
    

    【讨论】:

      【解决方案4】:

      您的实际情况无法工作,因为HashMap&lt;Integer,Integer&gt; 无法存储两个具有与1,101,11 相同的密钥的对。

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

      【讨论】:

        猜你喜欢
        • 2020-07-27
        • 1970-01-01
        • 2020-09-22
        • 1970-01-01
        • 2015-01-15
        • 1970-01-01
        • 2015-10-09
        • 2020-10-04
        • 1970-01-01
        相关资源
        最近更新 更多