繁体   English   中英

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

[英]Iterating over a HashSet and removing multiple elements in each iteration

在下面的代码中,我试图获取最大为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
        }
    }

现在在if语句中,我想从质primes删除perms中的所有元素。 答案显示了如何删除iterator指向的一个元素。 甚至有可能在一次迭代中从circularPrimes中删除多个元素? 如果是,请帮助。

迭代器仅允许您删除当前元素。 对于您的情况,您无需删除任何内容。 我相信你想删除的原因是为了避免调用circularPrimes为一个数字,是一个先前遇到一些圆形素数。 在这种情况下,您可以简单地检查该数字是否已经是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