简体   繁体   中英

Iterating over a HashSet and removing multiple elements in each iteration

In the following code, I am trying to get a Set of circular primes up to maxPlusOne .

Set<Integer> primes = getPrimes(maxPlusOne); //Returns a set of all primes up to maxPlusOne ont including it
    Set<Integer> circularPrimes = new HashSet<>();

    Iterator<Integer> it = primes.iterator();
    while(it.hasNext()) {
        Set<Integer> perms = getAllRotations(it.next()); //Returns all rotations of an integer 123 => {123, 231, 312}

        if(primes.containsAll(perms)) {
            circularPrimes.addAll(perms);
            // Here I want to do something to the effect of removing all elements in perms from primes
        }
    }

Now inside the if statement I want to remove all elements in perms from primes . This answer shows how to remove one element that the iterator is pointing to. Is it even possible to remove multiple elements from circularPrimes in one iteration? If yes, please help.

The Iterator allows you to remove only the current element. For your case, you need not remove anything. I believe the reason you would like to remove is to avoid calling circularPrimes for a number that is a circular prime of a previously encountered number. In that case, you can simply check if the number is already part of the circularPrimes set - if yes don't call getAllRotations

while(it.hasNext()) {
    Integer currentNum = it.next();
    if (!circularPrimes.contains(currentNum)) {
        Set<Integer> perms = getAllRotations(currentNum); 

        if(primes.containsAll(perms)) {
            circularPrimes.addAll(perms); 
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM