title: iterating through collection - removing other element
body: <p>What do I have to do if I would like to remove not only element my iterator points now, but also another one? Task is to write out pairs that sum up to some value (they are stored in HashSet set). Idea: iterate through the set, find second element that sum to what I need, write them out and remove from set both. What I mean, if my set is: [1,2,3] and int sum = 4, then I iterate through, find element 1st: 1, check 4 - 1 = 3, write out (1,3), and then I would like to remove 1 and 3 from the set so that only {2} left. I cannot do this that way of course:</p>
  
  <pre><code>while (itr.hasNext()) {
    int elem = itr.next();
    int toSum = sum - elem;
    if (set.contains(toSum)) {
      System.out.println("(" + elem + "," + toSum + ")");
    }
    itr.remove();
    set.remove(toSum);
  }
  </code></pre>
  
  <p>because of concurrent exception. I found out that solution:</p>
  
  <pre><code>while (itr.hasNext()) {
    HashSet&lt;Integer&gt; notNeeded = new HashSet&lt;Integer&gt;();
    int elem = itr.next();
    if (notNeeded.contains(elem)) {
      itr.remove();
    }
    else {
      int toSum = sum - elem;
      if (set.contains(toSum)) {
        System.out.println("(" + elem + "," + toSum + ")");
        notNeeded.add(toSum);
      }
      itr.remove();
    }
  }
  </code></pre>
  
  <p>but that does not look elegant and efficient (especially space efficient). Is there any better way to do this?</p>