在这个问题中,我必须找到两个映射中所有匹配的键/值映射,然后将其返回到一个新映射中,但我遇到了一些问题。我的想法是从两个映射中找到所有匹配的键,然后使用这些键将其引用到值。如果值匹配,我会将键/值放入映射中。我试图找出为什么它只是添加所有共同的键;仅当相应的值也匹配时,它才会添加这些键。谢谢。
提示:
编写一个 intersect 方法,该方法将两个字符串到整数的映射作为参数,并返回一个新映射,其内容是两者的交集。两个映射的交集在这里定义为两个映射中都存在的键和值的集合。因此,如果某个键 K 映射到第一个和第二个映射中的值 V,请将其包含在结果中。如果 K 在两个映射中都不作为键存在,或者如果 K 在两个映射中没有映射到相同的值 V,则从结果中排除该对。例如,考虑以下两个 map :
{Janet=87, Logan=62, Whitaker=46, Alyssa=100, Stefanie=80, Jeff=88, Kim=52, Sylvia=95}
{Logan=62, Kim=52, Whitaker=52, Jeff=88, Stefanie=80, Brian=60, Lisa=83, Sylvia=87}
在前面的映射上调用您的方法将返回以下新映射(键/值对的顺序无关紧要):
{Logan=62, Stefanie=80, Jeff=88, Kim=52}
我的代码:
// we need to store the keys, then get the values in common, then put the key/map into map
public static Map<String, Integer> intersect(Map<String, Integer> first, Map<String, Integer> second) {
Map<String, Integer> output = new HashMap<String, Integer>(first); // combined output
Set<String> keyFirst = new HashSet<String>(); // stores all the keys for first
for (String key: first.keySet()) { // goes through each key in input
keyFirst.add(key); // adds all keys from first into keyFirst
}
// goes through each key in common and checks to see if they reference to the same value
Iterator<String> keyFirstItr = keyFirst.iterator();
while (keyFirstItr.hasNext()) {
String keyTemp = keyFirstItr.next();
if (first.get(keyTemp) == second.get(keyTemp)) { // If same key, same value mapped
output.put(keyTemp, first.get(keyTemp)); // add key value to map
}
}
return output;
}
最佳答案
您可以通过将所有值传递给构造函数来将其从第一个值输出到输出。
Map<String, Integer> output = new HashMap<String, Integer>(first); // you are passing first to the constructor.
您不需要创建另一个 Set,keySet() 方法返回 set,因此不需要以下行。
Set<String> keyFirst = new HashSet<String>(); // stores all the keys for first
for (String key: first.keySet()) { // goes through each key in input
keyFirst.add(key); // adds all keys from first into keyFirst
}
这是正确的实现。
// we need to store the keys, then get the values in common, then put the key/map into map
public static Map<String, Integer> intersect(Map<String, Integer> first, Map<String, Integer> second) {
Map<String, Integer> output = new HashMap<String, Integer>(); // combined output
// goes through each key in common and checks to see if they reference to the same value
Iterator<String> keyFirstItr = first.keySet().iterator();
while (keyFirstItr.hasNext()) {
String keyTemp = keyFirstItr.next();
if (first.get(keyTemp).equals(second.get(keyTemp))) { // If same key, same value mapped
output.put(keyTemp, first.get(keyTemp)); // add key value to map
}
}
return output;
}
关于java - 在映射中查找匹配的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473999/