Write a method intersect that accepts two maps whose keys are strings and whose values are integers as parameters and returns a new map containing only the key/value pairs that exist in both of the parameter maps. In order for a key/value pair to be included in your result, not only do both maps need to contain a mapping for that key, but they need to map it to the same value. For example, if the two maps passed are {Janet=87, Logan=62, Whitaker=46,Alyssa=100, Stefanie=80, Jeff=88, Kim=52, Sylvia=95} and {Logan=62, Kim=52, Whitaker=52,Jeff=88, Stefanie=80, Brian=60, Lisa=83, Sylvia=87}, your method would return the following new map (the order of the key/value pairs does not matter): {Logan=62, Stefanie=80, Jeff=88, Kim=52}
package collections;
import java.util.HashMap;
import java.util.Map;
public class IntersectionMap {
public static HashMap<String, Integer> intersect(HashMap<String, Integer> map1, HashMap<String, Integer> map2) {
HashMap<String, Integer> newMap = new HashMap<String, Integer>();
// loop over all the keys in map1 and compare the keys and values in map1 and
// map2
for (String key : map1.keySet()) {
if (map2.containsKey(key) && map1.get(key) == map2.get(key))
newMap.put(key, map1.get(key));
}
// return our new map
return newMap;
}
public static void printMap(HashMap<String, Integer> map) {
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
public static void main(String[] args) {
HashMap<String, Integer> map1 = new HashMap<String, Integer>();
map1.put("Janet", 87);
map1.put("kishore", 123);
map1.put("william", 89);
map1.put("vanila", 35);
map1.put("marty", 123);
HashMap<String, Integer> map2 = new HashMap<String, Integer>();
map2.put("kishore", 17823);
map2.put("william", 89);
map2.put("vanila", 351);
map2.put("marty", 123);
System.out.println("Common key-value pairs in both maps are: ");
printMap(intersect(map1, map2));
}
}
Output:
Common key-value pairs in both maps are:
william : 89
marty : 123