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}.
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