Write a method called subMap that accepts two maps from strings to strings as its parameters and returns true if every key in the first map is also contained in the second map and maps to the same value in the second map. For example, {Smith=949–0504, Marty=206–9024} is a submap of {Marty=206–9024, Hawking=123–4567,Smith=949–0504, Newton=123–4567}. The empty map is a submap of every map.
package collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class SubMap {
// this method takes two maps as arguments
public static boolean isSubMap(Map<String, String> map, Map<String, String> map1) {
// check if the maps is null or empty
if (map == null || map.isEmpty() && !map1.isEmpty())
return true;
/* entrySet() gives both key value pairs of a map
we use containAll method to check if the other map
contains all the values of first map and return true if it contains
otherwise return false */
return map1.entrySet().containsAll(map.entrySet());
}
public static void main(String[] args) {
Map<String, String> map1 = new HashMap<String, String>();
map1.put("Smith", "949–0504");
map1.put("Marty", "206–9024");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("Marty", "206–9024");
map2.put("Hawking", "123–4567");
map2.put("Smith", "949–0504");
System.out.println(" map1 is submap of map2: " +isSubMap(map1,map2));
}
}
Output:
map1 is submap of map2: true