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);
Instead of a plain Map
use Google Guava's Multimap
.
A Multimap
is a
...collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values.
This concept has of course been implemented in other libraries as well, Guava is just my personal preference.
HashMap will only store 1 value for each Integer. So iterating over it should only gives you the following values:
Key Value
1 12
2 20
3 31
To iterate over the content of a Map you can use the entrySet() method:
for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
To build a Map of List, I recommand doing this:
List<Integer> list = map.get(key);
if(list == null) {
list = new ArrayList<Integer>();
map.put(key, list);
}
list.add(value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With