循环散列映射以将相同键的值分组到<键,列表<值>>对 [英] Looping through hashmap to group the values of same key into a <key, list<values>> pair
问题描述
我一直在努力想办法创建一个HashMap,它将具有相同密钥的值组合到一个列表中。这就是我的意思:
说我有以下键和值:
Value Key *对不起,我得到了交换列
1 10
1 11
1 12
2 20
3 30
3 31
我想将这些值放入
散列图<整数,列表<整数>>
因此,它会将这些值分组到具有相同键的List Integer中,如下所示:
$ b $(1,{10,11,12}),(2,{20}),(3,{30,31})
现在,键和值存储在
Hashmap< Integer,Integer> ;
我忘记了如何通过这个Hashmap来创建新的Hashmap:值列表对。有没有人有一个很好的方法来解决这个问题?解析方案
假设你创建了一个 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);
$ / code>
在您的示例数据中使用此方法:
HashMap<整数,列表<整数>> 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);
I've been having a hard time trying to think of a way create a HashMap that groups values (into a list) that has the same key. This is what I mean:
Say I have the following keys and values:
Value Key *Sorry I got the columns swapped
1 10
1 11
1 12
2 20
3 30
3 31
I would like to put these values into a
Hashmap <Integer, List<Integer>>
So that it will group the values into the List Integer that has the same key, something like this:
(1, {10, 11, 12}),(2, {20}), (3, {30,31})
Right now the key and the value are stored in a
Hashmap <Integer, Integer>
And I'm lost at how to loop through this Hashmap to create the new Hashmap with the key: List of Values pair. Does anyone have a good approach to this topic?
Suppose you create a HashMap<Integer, List<Integer>>
, and you want to add a key-value pair to it the way you asked, you can use the following method:
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);
}
Using this method with your example data:
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);
这篇关于循环散列映射以将相同键的值分组到<键,列表<值>>对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!