288

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 ?
Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
user496949
  • 83,087
  • 147
  • 309
  • 426
  • 9
    To be fair, this is a much better question than the original. Clear, well-written, and to the point. Even though the eventual answer is the same, the other question is all words--and focuses on efficiency, not simply getting the job done. However, for Java 8+ this may be the better answer: https://stackoverflow.com/a/39902694/1339923 – Lambart Jan 08 '19 at 18:22

2 Answers2

531

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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • 3
    Just a note for anyone looking to use retainAll on another Collection, such as a list with duplicate elements. Depending on the contents of the collection you can throw an UnsupportedOperationException, and it also won't filter frequencies correctly (it retains any and all occurrences of a value in the left multiset, regardless of how many times it occurs in the right multiset). – Allison Jan 17 '18 at 09:54
74

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Emmanuel N
  • 7,350
  • 2
  • 26
  • 36