Possible Duplicate:
Efficiently finding the intersection of a variable number of sets of strings
Say, have two Hashset, how to calculate the intersection of them?
Set<String> s1 = new HashSet<String>();
Set<String> s2 = new HashSet<String>();
S1 INT S2 ?
Use the retainAll() method of Set :
Set<String> s1; Set<String> s2; s1.retainAll(s2); // s1 now contains only elements in both setsIf you want to keep the sets, create a new set to contain the intersection:
Set<String> intersection = new HashSet<String>(s1); // use the copy constructor intersection.retainAll(s2); The retainAll() javadoc says that is exactly what you want:
Keeps only the elements of this set that are contained in the specified collection (optional operation). In other words, it removes from this set all 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.