title: Efficiently compute Intersection of two Sets in Java?
body: <p>What is the most efficient way to find the size of the intersection of two non-sparse Sets in Java? This is an operation I will be calling on large sets a very large number of times, so optimisation is important. I cannot modify the original sets.</p>
  
  <p>I have looked at Apache Commons CollectionUtils.intersection which appears to be quite slow. My current approach is to take the smaller of the two sets, clone it, and then call .retainAll on the larger of the two sets.</p>
  
  <pre><code>public static int getIntersection(Set&lt;Long&gt; set1, Set&lt;Long&gt; set2) {
      boolean set1IsLarger = set1.size() &gt; set2.size();
      Set&lt;Long&gt; cloneSet = new HashSet&lt;Long&gt;(set1IsLarger ? set2 : set1);
      cloneSet.retainAll(set1IsLarger ? set1 : set2);
      return cloneSet.size();
  }
  </code></pre>