简体   繁体   English

迭代HashSet并在每次迭代中删除多个元素

[英]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 . 在下面的代码中,我试图获取最大为maxPlusOneSet 圆形素数

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 . 现在在if语句中,我想从质primes删除perms中的所有元素。 This answer shows how to remove one element that the iterator is pointing to. 答案显示了如何删除iterator指向的一个元素。 Is it even possible to remove multiple elements from circularPrimes in one iteration? 甚至有可能在一次迭代中从circularPrimes中删除多个元素? 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. 我相信你想删除的原因是为了避免调用circularPrimes为一个数字,是一个先前遇到一些圆形素数。 In that case, you can simply check if the number is already part of the circularPrimes set - if yes don't call getAllRotations 在这种情况下,您可以简单地检查该数字是否已经是circularPrimes集合的一部分-如果是,则不要调用getAllRotations

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

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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