【问题标题】:Iterating over a HashSet and removing multiple elements in each iteration遍历 HashSet 并在每次迭代中删除多个元素
【发布时间】:2018-10-01 08:33:31
【问题描述】:

在下面的代码中,我试图得到一个Setcircular primes 直到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
        }
    }

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

【问题讨论】:

    标签: java iterator hashset


    【解决方案1】:

    Iterator 允许您仅删除当前元素。对于您的情况,您无需删除任何内容。我相信您要删除的原因是避免调用 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); 
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-30
      • 2021-01-08
      • 2020-06-09
      • 2010-11-09
      • 2014-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多