In: Computer Science
In java.
Write a method static <K, V> void addToMultiMap(Map<K, Set<V>> map, K key, V value). addToMultiMap must add the value, if present, to the set associated with the given key, creating the set if necessary. You may assume all keys already in the map are associated with non-null values.
For full credit, your method must include generic types, and must not contain unnecessary method calls or loops, even if they do not otherwise impact correctness. You may assume Map, Set, HashMap, and HashSet are correctly imported from java.util. You may not import other classes.
A generic method is a method which can take any type of argument and perform a certain operation(which is adding to the map in this case).
Kindly find belwo the generic method addToMultiMap(Map<K, Set<V>> map, K key, V value):
import java.util.*;
public class MultiMap {
public static <K, V> void addToMultiMap(Map<K, Set<V>> map, K key, V value){
Set<V> set = new HashSet<>();
if (map.get(key) != null)
set = map.get(key);
set.add(value);
map.put(key, set);
}
public static void main(String[] args){
Map<Integer, Set<String>> map = new HashMap<>();
addToMultiMap(map, 1, "kapil");
addToMultiMap(map, 2, "raman");
addToMultiMap(map, 3, "gaveesh");
addToMultiMap(map, 1, "kapil");
System.out.println(map);
Map<Integer, Set<Integer>> mapTwo = new HashMap<>();
addToMultiMap(mapTwo, 1, 11);
addToMultiMap(mapTwo, 2, 22);
addToMultiMap(mapTwo, 3, 33);
addToMultiMap(mapTwo, 1, 11);
System.out.println(mapTwo);
}
}
Output of above program is as follows:
{1=[kapil], 2=[raman], 3=[gaveesh]}
{1=[11], 2=[22], 3=[33]}