JAVA Write a static method named conflicts that takes two Maps using Strings as
ID: 644270 • Letter: J
Question
JAVA
Write a static method named conflicts that takes two Maps using Strings as keys and Integers as values. The method should return a Set of Strings. The Set returned by conflicts should be a list of all of the keys that are in conflict between the two Maps. A conflict occurs when two keys point to a different value in the two different maps. (For example, map1 might have the key "Apple" pointing to the Integer 12 and map2 might have the key "Apple"pointing to the Integer 15 - the key "Apple" would need to be added to the Set of conflicts returned by the method).
Explanation / Answer
import java.util.*;
public class Conflicts {
public static Set<String> conflicts(Map m1, Map m2){
Set<String> r = new HashSet<String>();
Object[] arr = m1.keySet().toArray();
for(int i = 0; i < arr.length; ++i){
if(!m2.containsKey(arr[i]) || (m1.get(arr[i]) != m2.get(arr[i]))){
r.add((String) arr[i]);
}
}
return r;
}
public static void main(String args[]){
Map fruits1 = new HashMap();
Map fruits2 = new HashMap();
fruits1.put("Apple", 5);
fruits1.put("Mango", 3);
fruits1.put("Orange", 4);
fruits1.put("Grape", 10);
fruits2.put("Apple", 7);
fruits2.put("Mango", 3);
fruits2.put("Orange", 6);
fruits2.put("Grape", 10);
Set<String> s = conflicts(fruits1, fruits2);
System.out.println(s);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.