SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Java Collections Framework
Exercise:
Exercises
Question:17 | ISBN:9780136091813 | Edition: 2

Question

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.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.