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?
Java 8 Stream interface introduces filter() method which can be used to filter out some elements from object collection based on a particular condition. This condition should be specified as a predicate which the filter() method accepts as an argument. The java. util.
You can filter Java Collections like List, Set or Map in Java 8 by using the filter() method of the Stream class. You first need to obtain a stream from Collection by calling stream() method and then you can use the filter() method, which takes a Predicate as the only argument.
ArrayList removeIf() method in Java The removeIf() method of ArrayList is used to remove all of the elements of this ArrayList that satisfies a given predicate filter which is passed as a parameter to the method.
With Java 8, you can filter with a lambda expression using Collection.removeIf
.
cars.removeIf(c -> c.getCarColor() == Color.BLUE);
Maybe you could use iterators, which are a little more efficient:
public void removeAllBlueCars() { Iterator<Car> carsIterator = cars.iterator(); while (carsIterator.hasNext()) { Car c = carsIterator.next(); if (c.getCarColor() == Color.BLUE) { carsIterator.remove(); } } }
Also, if you want to make this solution more generic, I'd suggest you something like:
public interface Filter<T> { public boolean shouldRemove(T t); }
And you could use it like this:
public void removeCars(Filter<Car> filter) { Iterator<Car> carsIterator = cars.iterator(); while (carsIterator.hasNext()) { Car c = carsIterator.next(); if (filter.shouldRemove(c)) { carsIterator.remove(); } } }
Your method gets called like this:
removeCars(new Filter<Car>() { public boolean shouldRemove(Car car) { return car.getCarColor() == Color.BLUE; } });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With