Remove elements from a HashSet on iteration

Suppose I have HashSet


[1, 2, 3, 4, 5, 6]


I want to iterate over it in such a way that for a given sum, say 6, iterating over the elements, if I find 2 elements in Set

that have sum = 6, I want to delete another one. E. g., If I repeat more than 1, I have to delete 5. I tried to do something like this:

HashSet<Integer> hs = new HashSet(arr);
int sum = 6;
for(int num : hs) {
    if(hs.contains(sum - num)) {
        hs.remove(sum - num);


Obviously he is throwing away java.util.ConcurrentModificationException

. Another approach is to use an iterator, but it removes the current element and does not take any other element as a parameter. What else can I use?

Update: I know the methods of using the extra set and all. I just wanted a very optimal solution, without increasing time and space if possible.


source to share

2 answers

Save the running set of numbers you find.

This will allow you to have a one-pass solution.

Start with an empty set of starts and repeat the set of numbers. For each item you iterate over, if its compliment sum is in the set, remove it from the iterator. If not, add it to the working set.

HashSet<Integer> hs = new HashSet(arr);
HashSet<Integer> running = new HashSet();
int sum = 6;
Iterator<Integer> iter = hs.iterator();
while (iter.hasNext()) {
    int num =;
    if (running.contains(sum - num)) {
    } else {


This code will change the original HashSet

, and both HashSet

will contain the same content at the end of the code block. In this case, it would be better to just use the running

one set at the end of the code and not modify the original. This will make this code more flexible and reusable.



you can use a sorted list instead. first collect the numbers in ascending order. then you put 2 iterators one on the first element and the others on the last element. then at each step, if the sum of 2 elements under the iterators is less than your desired number, you must increment the first iterator, if its a grater you should decrement the second iterator, and if it is equal to what you want, you select and increment them first and decrement second iterator.

it works faster than a set!



All Articles