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