title: Arraylist Intersection performance (in time and space ) in Java
body: <p>I need to make million of intersections of ArrayList in java, and for this purpose I use this method:</p>
  
  <pre><code>public static ArrayList&lt;Integer&gt; intersection(ArrayList&lt;Integer&gt; a, ArrayList&lt;Integer&gt; b) {
          Set&lt;Integer&gt; aSet = new HashSet&lt;Integer&gt;(a);
          Set&lt;Integer&gt; bSet = new HashSet&lt;Integer&gt;(b);
  
          for(Iterator&lt;Integer&gt; it = aSet.iterator(); it.hasNext();) {
              if(!bSet.contains(it.next())) it.remove();
          }
          return new ArrayList&lt;Integer&gt;(aSet);
      }
  </code></pre>
  
  <p>In terms of time It's performant But I have a lot of memory leaks and I often go out of memory. How can I improve the function in order to be performant both in time and in space?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>The arraylists given in input must remain unchanged.</p>