You can manually iterate over the elements of the set:
Iterator<Integer> iterator = set.iterator();
while (iterator.hasNext()) {
Integer element = iterator.next();
if (element % 2 == 0) {
iterator.remove();
}
}
You will often see this pattern using a for
loop rather than a while
loop:
for (Iterator<Integer> i = set.iterator(); i.hasNext();) {
Integer element = i.next();
if (element % 2 == 0) {
i.remove();
}
}
As people have pointed out, using a for
loop is preferred because it keeps the iterator variable (i
in this case) confined to a smaller scope.