Created
January 23, 2018 13:57
-
-
Save pozdneev/0bb8e1d788310cbe7d2bd62969bcfff6 to your computer and use it in GitHub Desktop.
How to remove an element from a collection while iterating over it
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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