Use an Iterator and remove the item with Iterator.remove() : Iterator « Collections Data Structure « Java
- Java
- Collections Data Structure
- Iterator
Use an Iterator and remove the item with Iterator.remove()
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
String s = iter.next();
if (s.equals("B")) {
iter.remove();
} else {
System.out.println(s);
}
}
for (String s : list) {
System.out.println(s);
}
}
}
Related examples in the same category