I have two ArrayList as follows:
original: 12, 16, 17, 19, 101
selected: 16, 19, 107, 108, 109
Here is a function to find intersection of various collections (more than 2) -
public static > C findIntersection(C newCollection,
Collection... collections) {
boolean first = true;
for (Collection collection : collections) {
if (first) {
newCollection.addAll(collection);
first = false;
} else {
newCollection.retainAll(collection);
}
}
return newCollection;
}
Usage -
public static void main(String[] args) {
List l1 = List.of(1, 3, 5, 7, 9, 11, 13);
List l2 = List.of(1, 2, 3, 5, 8, 13);
List l3 = List.of(2, 3, 5, 7, 11, 13);
Set intersection = findIntersection(new HashSet<>(), l1, l2, l3);
System.out.println(intersection);
}