簡體   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