private static class FilterByStringContains implements Predicate<String> {
private String filterString;
private FilterByStringContains(final String filterString) {
this.filterString = filterString;
}
@Override
public boolean apply(final String string) {
return string.contains(filterString);
}
}
I have a list of Strings, I want to filter it by the specified String so the returned value contains a list of only the specified strings. I was going to use a predicate as above but not sure how to apply this to filter a list
One of the utility method filter() helps to filter the stream elements that satisfy the provided criteria. The predicate is a functional interface that takes a single element as an argument and evaluates it against a specified condition.
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.
I'm assuming the Predicate
here is from Guava? If so, you could use Iterables.filter
:
Iterable<String> filtered = Iterables.filter(original, predicate);
Then build a list from that if you wanted:
List<String> filteredCopy = Lists.newArrayList(filtered);
... but I'd only suggest copying it to another list if you actually want it as a list. If you're just going to iterate over it (and only once), stick to the iterable.
How about using Guava's filter method or Apache commons' filter method? Guava's method returns a view of the collection, whereas Apache Commons' modifies the collection in-place. Don't reinvent the wheel!
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