title: Remove Elements from a HashSet while Iterating
body: <p>So, if I try to remove elements from a Java <em>HashSet</em> while iterating, I get a <em>ConcurrentModificationException</em>.  What is the best way to remove a subset of the elements from a <em>HashSet</em> as in the following example?</p>
  
  <pre><code>Set&lt;Integer&gt; set = new HashSet&lt;Integer&gt;();
  
  for(int i = 0; i &lt; 10; i++)
      set.add(i);
  
  // Throws ConcurrentModificationException
  for(Integer element : set)
      if(element % 2 == 0)
          set.remove(element);
  </code></pre>
  
  <p>Here is a solution, but I don't think it's very elegant:</p>
  
  <pre><code>Set&lt;Integer&gt; set = new HashSet&lt;Integer&gt;();
  Collection&lt;Integer&gt; removeCandidates = new LinkedList&lt;Integer&gt;();
  
  for(int i = 0; i &lt; 10; i++)
      set.add(i);
  
  for(Integer element : set)
      if(element % 2 == 0)
          removeCandidates.add(element);
  
  set.removeAll(removeCandidates);
  </code></pre>
  
  <p>Thanks!</p>