In: Computer Science
Given the nested collection that maps each term to a set of strings
Return a string of terms that are repeated in all the nested sets
Given :
{apple=[apple BALL carrot, ball !carrot! ,!Dog*&]}
{apple=[apple BALL carrot, ball !carrot! ,!Dog*&], dog=[ball !carrot! ,!Dog*&]}
Return:
[ball !carrot! ,!Dog*&]
Public static String common(Map<String, Set<Sting>> map)
{
}
Ans)
Java program
import java.util.*;
class CommonInSet {
public static void main(String[] args) {
Set<String> s1 = new HashSet<String>();
s1.add("apple BALL carrot");
s1.add("ball !carrot!");
s1.add("!Dog*&");
System.out.println("Set 1: " + s1);
Set<String> s2 = new HashSet<String>();
s2.add("ball !carrot!");
s2.add("!Dog*&");
System.out.println("Set 1: " + s2);
Map<String, Set<String>> m = new HashMap<String, Set<String>>();
m.put("apple", s1);
m.put("dog", s2);
System.out.println("Map: " + m);
System.out.println("Finding the common elements: ");
Set<String> intersectionSet = new HashSet<String>();
intersectionSet = common(m);
System.out.println("Common Elements: " + intersectionSet);
}
public static Set<String> common(Map<String, Set<String>> map) {
if (map == null)
return null;
Set set = map.entrySet();
Iterator itr = set.iterator();
Map.Entry entry = (Map.Entry) itr.next();
Set<String> intersectionSet = new HashSet<String>();
intersectionSet = (Set) entry.getValue();
while (itr.hasNext()) {
entry = (Map.Entry) itr.next();
intersectionSet.retainAll((Set) entry.getValue());
}
return intersectionSet;
}
}
Above compile and execute Java program and get output below screen shot here
Output
******************End*****"*****"**************
if your satisfy above answer please give positive rating or upvote
please don't downvote
if any doubts below comment here
Thankyou!