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

This question already has answers here: Efficiently finding the intersection of a variable number of sets of strings (8 answers) Closed 1 year ago. 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> … Read more

How to calculate 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 … Read more