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:14 | ISBN:9780136091813 | Edition: 2

Question

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}

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

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

 

0 0

Discussions

Post the discussion to improve the above solution.