Write a method intersect that takes two Maps of strings to integers as parameter
ID: 3938014 • Letter: W
Question
Write a method intersect that takes two Maps of strings to integers as parameters and that returns a new map whose contents are the intersection of the two. The intersection of two maps is defined here as the set of keys and values that exist in both maps. So if some key K maps to value V in both the first and second map, include it in your result. If K does not exist as a key in both maps, or if K does not map to the same value V in both maps, exclude that pair from your result. For example, consider the following two maps: {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} Calling your method on the preceding maps would return the following new map (the order of the key/value pairs does not matter): {Logan=62, Stefanie=80, Jeff=88., Kim=52} Type your solution here: public static Map intersect(Map map1, Map map2) {}Explanation / Answer
public static Map<String,Integer> intersect(Map<String,Integer> map1,Map<String,Integer> map2)
{
Map<String,Integer> map3=new HashMap<String,Integer>();
for(String s:map1.keySet())
{
for(String s1:map2.keySet())
{
if(s1.equalsIgnoreCase(s))
{
map3.put(s,map1.get(s));
map2.remove(s);
}
}
return map3;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.