Skip to content

Instantly share code, notes, and snippets.

@pozdneev
Created January 23, 2018 13:57
Show Gist options
  • Save pozdneev/0bb8e1d788310cbe7d2bd62969bcfff6 to your computer and use it in GitHub Desktop.
Save pozdneev/0bb8e1d788310cbe7d2bd62969bcfff6 to your computer and use it in GitHub Desktop.
How to remove an element from a collection while iterating over it
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
public class IteratorRemove {
static public void main(String[] args) {
// Populate a collection
Collection<Integer> ll = new LinkedList<>();
for (int i = 0; i < 10; ++i) {
ll.add(i);
}
// Remove some element
Iterator<Integer> iter = ll.iterator();
while (iter.hasNext()) {
Integer val = iter.next();
if (val.intValue() == 5) {
iter.remove();
}
}
// Print the collection
for (Integer i : ll) {
System.out.print(i.intValue() + " ");
}
System.out.println();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment