Yes, using Collection#removeIf(Predicate)
:
Removes all of the elements of this collection that satisfy the given predicate.
Note that it will change the given collection, not return a new one. But you can create a copy of the collection and modify that. Also note that the predicate needs to be negated to act as a filter:
public static <E> Collection<E> getFilteredCollection(Collection<E> unfiltered,
Predicate<? super E> filter) {
List<E> copyList = new ArrayList<>(unfiltered);
// removeIf takes the negation of filter
copyList.removeIf(e -> { return !filter.test(e);});
return copyList;
}
But as @Holger suggests in the comments, if you choose to define this utility method in your code and use it everywhere you need to get a filtered collection, then just delegate the call to the collect
method in that utility. Your caller code will then be more concise.
public static <E> Collection<E> getFilteredCollection(Collection<E> unfiltered,
Predicate<? super E> filter) {
return unfiltered.stream()
.filter(filter)
.collect(Collectors.toList());
}