Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the intersection of two sets? [duplicate]

People also ask

What is the intersection of two identical sets?

Definition: The intersection of two sets, X and Y, is the set of elements that are common to both X and Y. It is denoted by X ∩ Y, and is read "X intersect Y". So the intersection of two sets is the set of elements common to both sets.

What is the formula of intersection of two sets?

The intersection of two or more given sets is the set of elements that are common to each of the given sets. The intersection of sets is denoted by the symbol '∩'. In the case of independent events, we generally use the multiplication rule, P(A ∩ B) = P( A )P( B ).

How do you find the intersection of two sets in Java?

intersection() returns an unmodifiable view of the intersection of two sets. The returned set contains all elements that are contained by both backing sets. The iteration order of the returned set matches that of set1. Return Value: This method returns an unmodifiable view of the intersection of two sets.


Use the retainAll() method of Set:

Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets

If you want to preserve the sets, create a new set to hold the intersection:

Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);

The javadoc of retainAll() says it's exactly what you want:

Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.


Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);