[英]Iterating over a HashSet and removing multiple elements in each iteration
在下面的代碼中,我試圖獲取最大為maxPlusOne
一Set
圓形素數 。
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.