在这个问题中,我必须有一个包含字符串键和值的映射,以查看多个键是否映射到相同的值。换句话说,如果没有两个键映射到相同的值,我的方法应该返回 true,否则返回 false。我试图解决这个问题是将所有 map 放入一个集合中并检查每个元素以查看是否有相同值的两个副本;但是,这似乎对我不起作用。任何建议将不胜感激,谢谢。
提示:
编写一个 isUnique 方法,它接受一个从字符串到字符串的映射作为参数,如果没有两个键映射到相同的值,则返回 true(如果任何两个或更多键映射到相同的值,则返回 false)。例如,在以下 map 上调用您的方法将返回 true:
{Marty=Stepp, Stuart=Reges, Jessica=Miller, Amanda=Camp, Hal=Perkins}
在下面的 map 上调用它会返回 false,因为 Perkins 和 Reges 有两个映射:
{Kendrick=Perkins, Stuart=Reges, Jessica=Miller, Bruce=Reges, Hal=Perkins}
空 map 被认为是唯一的,因此如果传递空 map ,您的方法应返回 true。
我的尝试:
public static boolean isUnique(Map<String, String> input) {
Collection<String> values = input.values(); // stores all the values into a collection
for (String names: values) { // goes through each string to see if any duplicates
Iterator<String> wordList = values.iterator(); // iterates words in values collection
int repeat = 0; // counts number of repeats
// goes through each elem to compare to names
if (wordList.hasNext()) {
if (wordList.next().equals(names)) {
repeat++;
}
}
if (repeat > 1) { // if more than one copy of the value exists = multiple keys to same value
return false; // If multiple copies of same value exists
}
}
return true; // all unique values
}
最佳答案
如果我理解你的问题,那么我会像这样一般地实现你的方法 -
public static <K, V> boolean isUnique(Map<K, V> input) {
if (input == null || input.isEmpty()) {
return true;
}
Set<V> set = new HashSet<V>();
for (V value : input.values()) {
set.add(value);
}
return set.size() == input.size();
}
关于java - 查找多个键是否映射到相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473364/