So the structure is {{Dog,Cat,Human},{Human,Dog,Whale,rabbit,Cow},{Monkey,Human,Dog}}.
Output should be: Dog,Human.
I have to find the intersection of ArrayList elements (Strings, for now. Could be integers as well) inside the bigger ArrayList. Previously, I have seen codes of finding the intersection of separate ArrayLists, but not sure how I could do it inside the same ArrayList.
For separate ArrayLists a code like the following works. But how do I make it work for multiple ArrayLists inside one ArrayList? I was asked this in an interview. Worked for separate lists, but when the interviewer asked this, I couldn't code it out for the same ArrayList.
public class Test {
public <String> List<String> intersection(List<String> list1, List<String> list2) {
List<String> list = new ArrayList<String>();
for (String t: list1) {
if(list2.contains(t)) {
list.add(t);
}
}
return list;
}
public static void main(String[] args) throws Exception {
List<String> list1 = new ArrayList<String>(Arrays.asList("Dog", "Cat", "Human"));
List<String> list2 = new ArrayList<String>(Arrays.asList("Human", "Dog", "Whale", "rabbit", "Cow"));
System.out.println(new Test().intersection(list1, list2));
}
}
This produces correct output for two separate ArrayLists.
Listis aListitself, you can callintersectionin a loop like you might calculate the sum of elements in aList<Integer>. \$\endgroup\$intersection's type parameter to be namedString? \$\endgroup\$