remove elements from for loop vs iterator
package com.java.forloopvsiterator.test;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
// show init lists
println("Initial List");
printArray(createList());
println("To Remove List");
printArray(createToRemoveList());
// foreach
testRemoveViaForEachLoop();
// iterator
testRemoveViaIterator();
}
private static void testRemoveViaIterator() {
println("Remove testRemoveViaIterator");
final List<?> array = createList();
try {
removeUsingIterator(array, createToRemoveList());
} catch (final ConcurrentModificationException e) {
e.printStackTrace();
}
printArray(array);
}
private static void testRemoveViaForEachLoop() {
println("Remove removeUsingForeach");
final List<?> array = createList();
try {
removeUsingForeach(array, createToRemoveList());
} catch (ConcurrentModificationException e) {
// slurp
}
printArray(array);
}
private static void removeUsingIterator(final List<?> list, final List<?> toRemove) {
for (Iterator<?> listIterator = list.iterator(); listIterator.hasNext(); ) {
final Object o = listIterator.next();
for (Iterator<?> toRemoveIterator = toRemove.iterator(); toRemoveIterator.hasNext(); ) {
final Object p = toRemoveIterator.next();
if (o.equals(p))
listIterator.remove();
}
}
}
private static void removeUsingForeach(final List<?> list, final List<?> toRemove) throws ConcurrentModificationException {
for (final Object o : list)
for (final Object p : toRemove)
if (o.equals(p))
list.remove(p);
}
private static List<?> createList() {
final ArrayList<String> strings = new ArrayList<String>();
for (char letter = 'a'; letter <= 'z'; ++letter)
strings.add(String.valueOf(letter));
return strings;
}
private static List<?> createToRemoveList() {
final ArrayList<String> strings = new ArrayList<String>();
for (char letter = 'e'; letter <= 'q'; ++letter)
strings.add(String.valueOf(letter));
return strings;
}
private static void printArray(final List<?> list) {
for (final Object o : list)
System.out.print(o + " ");
println("");
}
private static void println(final String msg) {
System.out.println(msg);
System.out.println();
}
}