Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to filter elements from a collection in Java?

Tags:

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?

like image 644
Frederik Avatar asked Sep 07 '10 09:09

Frederik


People also ask

What method is used to filter elements from a collection?

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.

How do you filter data in collections?

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.

How do you filter data in an ArrayList?

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.


2 Answers

With Java 8, you can filter with a lambda expression using Collection.removeIf.

cars.removeIf(c -> c.getCarColor() == Color.BLUE); 
like image 129
Jeffrey Bosboom Avatar answered Oct 15 '22 11:10

Jeffrey Bosboom


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;     }  }); 
like image 30
Vivien Barousse Avatar answered Oct 15 '22 10:10

Vivien Barousse