Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add multiple values to single key in java

Tags:

java

How can I create a map that can extend its list of value. For example I have a map which contains: key A and list of values B {1,2,3}. Then at some point during the program running, I would like to add more value, ex: 4 to list B. Now my new map should be something like: (A,{1,2,3,4}). How can I do that?

like image 455
Ock Avatar asked Nov 30 '22 09:11

Ock


1 Answers

Since Map<K,V> maps one key to one value, you need V to be of type List<T>:

Map<String,List<Integer>> multiMap = new HashMap<>();

One consequence of having a type like that is that now the process of adding an item to a key consists of two steps: you must check if the list for the key exists, and then either add a new item to an existing list, or add a new list with a single item:

List<Integer> current = multiMap.get(key);
if (current == null) {
    current = new ArrayList<Integer>();
    multiMap.put(key, current);
}
current.add(val);

If you use Java 8, you can use computeIfAbsent to greatly simplify the code:

multiMap.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
like image 59
Sergey Kalinichenko Avatar answered Dec 01 '22 23:12

Sergey Kalinichenko