Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing matching elements of a TreeSet

Tags:

java

set

I am trying to remove all numbers that is divisible with some index in a TreeSet and I am using the following code

    TreeSet<Integer> primes = new TreeSet();
    Iterator<Integer> iter = primes.iterator();

    int n = 100;            
    for (int i = n; i > 1; i--){
        primes.add(i);
    }

    for (int i = 2; i < Math.sqrt(n); i ++){
        while (iter.hasNext()){
            int next = iter.next();
            if (next % i == 0){
                primes.remove(next);
            }
        }
    }
    System.out.println(primes);

But for some reason, no elements in the set gets removed

like image 918
manis Avatar asked Sep 16 '25 21:09

manis


2 Answers

Iterator.remove() is the only safe way to modify a collection during iteration. Use iter.remove();

  while (iter.hasNext()){
        int next = iter.next();
        if (next % i == 0){
            iter.remove();
        }
    }

Removes from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method. From ITERATOR

like image 66
pratim_b Avatar answered Sep 18 '25 10:09

pratim_b


First create the Iterator after you added the primes and then use Iterator.remove() to not get a ConcurrentModificationException.

TreeSet<Integer> primes = new TreeSet();

    int n = 100;
    for (int i = n; i > 1; i--) {
        primes.add(i);
    }
    Iterator<Integer> iter = primes.iterator();

    for (int i = 2; i < Math.sqrt(n); i++) {
        while (iter.hasNext()) {
            int next = iter.next();
            if (next % i == 0) {
                iter.remove();
            }
        }
    }
    System.out.println(primes);
like image 32
René Link Avatar answered Sep 18 '25 11:09

René Link