Write a method called is1to1 that accepts a map whose keys and values are strings as its parameter and returns true if no two keys map to the same value. For example, {Marty=206–9024, Hawking=123–4567, Smith=949–0504,Newton=123–4567} should return false, but {Marty=206–9024, Hawking=555–1234, Smith=949–0504,Newton=123–4567} should return true. The empty map is considered 1-to-1 and returns true.
package collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class IsOneToOne {
// this method takes map class as argument
public static boolean is1To1(Map<String, String> map) {
// check if map is null or whether if it is empty
if (map == null || map.isEmpty())
return true;
Set<String> val = new HashSet<String>();
// try to add the values of map in set class, if it failed to add
// the value already exist and will return false otherwise true
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("kishore", "123");
map1.put("william", "89");
map1.put("vanila", "351");
map1.put("marty", "123");
// above map should return false
boolean check = IsOneToOne.is1To1(map1);
System.out.println(check);
// below map should return true
map1.put("kishore", "123");
map1.put("william", "89");
map1.put("vanila", "351");
map1.put("marty", "12345");
boolean check1 = IsOneToOne.is1To1(map1);
System.out.println(check1);
}
}
Output:
false
true