I want to write a method that removes all elements from a collection that follow a certain pattern. In functional languages, I would use filter() with a lambda expression. However, in Java, it seems I'm stuck with this:
public void removeAllBlueCars() {
LinkedList<Car> carsToRemove = new LinkedList<Car>();
for (Car c : cars) {
if (c.getCarColor() == Color.BLUE) {
carsToRemove.add(c);
}
}
cars.removeAll(carsToRemove );
}
Removing elements directly causes a ConcurrentModificationException. Is there a better way to do this without resorting to Google Collections?