I want to filter a java.util.Collection
based on a predicate.
Some really great great answers here. Me, I'd like to keep thins as simple and readable as possible:
public abstract class AbstractFilter {
/**
* Method that returns whether an item is to be included or not.
* @param item an item from the given collection.
* @return true if this item is to be included in the collection, false in case it has to be removed.
*/
protected abstract boolean excludeItem(T item);
public void filter(Collection collection) {
if (CollectionUtils.isNotEmpty(collection)) {
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
if (excludeItem(iterator.next())) {
iterator.remove();
}
}
}
}
}