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

Question

Write a method isUnique that accepts a map whose keys and values are strings as a parameter and returns true if no two keys map to the same value (and false if any two or more keys do map to the same value). For example, if the map contains the following key/value pairs, your method would return true: {Marty=Stepp, Stuart=Reges,Jessica=Miller, Amanda=Camp, Hal=Perkins}. But calling it on the following map would return false,because of two mappings for Perkins and Reges: {Kendrick=Perkins, Stuart=Reges, Jessica=Miller,Bruce=Reges, Hal=Perkins}.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package collections;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class UniqueMap {
	
    // this method takes two maps as parameters
	public static boolean isUnique(Map<String, String> map) {

        // check if map is null if it is empty
		if (map == null || map.isEmpty())
			return true;
        // create Hashset class which wont take duplicates
		Set<String> val = new HashSet<String>();

        // iterate the each value in the map and try to add it in the hashset
        // it return flase if failed to add...thus it already exist
		for (String value : map.values()) {
			boolean flag = val.add(value);
			if (!flag) {
				return false;
			}
			
		}
		return true;
	}
	
	public static void main(String[] args) {
		
		Map<String, String> map1 = new HashMap<String, String>();
		map1.put("Marty", "Stepp");
		map1.put("Stuart", "Stuart");
		map1.put("Jessica", "Miller");
		map1.put("Amanda", "Camp");
		map1.put("Camp", "Perkins");

		// above map should return false
		boolean check = isUnique(map1);
		System.out.println("No two keys point to same value in map1:" +check);
		// below map should return true
		map1.put("Kendrick", "Perkins");
		map1.put("Stuart", "Reges");
		map1.put("Jessica", "Miller");
		map1.put("Bruce", "Reges");
		map1.put("Hal", "Perkins");
		
		boolean check1 = isUnique(map1);
		
		System.out.println("No two keys point to same value in map2:" +check1);
	}

}
Output:

No two keys point to same value in map1:true
No two keys point to same value in map2:false

 

0 0

Discussions

Post the discussion to improve the above solution.