Deleting an element from Set Java error


I can't understand why the program compiles, but at startup it gives an error

*Generating a collection set [65, 1, 97, 66, 2, 69, 6, 71, 42, 14, 49, 19, 83, 20, 21, 53, 56, 59, 92, 29]

Exception in thread "main" java.util.ConcurrentModificationException
at java.base/java.util.HashMap$HashIterator.nextNode(HashMap.java:1584)
at java.base/java.util.HashMap$KeyIterator.next(HashMap.java:1607)
at JavaRushLect8.Collections.main(Collections.java:189)*



public static void main(String[] args) throws InterruptedException {

        Set<Integer> setOfInteger = new HashSet<>();
        randomInsert(setOfInteger, 20, 100);
      
        for (int i : setOfInteger) {
            if(i > 20)
            {
              setOfInteger.remove(i);
            }
        }

Although if you use - System.out.println(i) in the conditions block, everything works...

Author: Future Man, 2020-08-10

2 answers

You can't delete items from a collection while it is being sorted through.

I would suggest 2 options:

Set<Integer> result = setOfInteger.stream().filter(i -> i <= 20).collect(Collectors.toSet());

In this case, a new result collection is created with the values already filtered out.

And if you fundamentally need to remove elements from the original collection (it's better not to do this, but still), then the iterator will come to the rescue:

Iterator<Integer> iterator = setOfInteger.iterator();
while (iterator.hasNext()) {
    if (iterator.next() > 20) iterator.remove();
}
 2
Author: Дмитрий, 2020-08-10 19:54:33

You delete by iterating through the index in ascending order. Imagine you deleted 99 and the next one you want to delete 100 where does it come from if after deleting 99 you have 99 left in the set. Remove from collections by indexing in descending order. So that you do not return to the checked elements.

And to return the index without deleting anything from what there should be an error?

 0
Author: Aziz Umarov, 2020-08-10 19:42:16