My code looks like this:
List filterList(List list, String regex) {
List result = new ArrayList();
Google's Java library(Guava) has an interface Predicate<T>
which might be pretty useful for your case.
static String regex = "yourRegex";
Predicate<String> matchesWithRegex = new Predicate<String>() {
@Override
public boolean apply(String str) {
return str.matches(regex);
}
};
You define a predicate like the one above and then filter your list based on this predicate with a single-line code:
Iterable<String> iterable = Iterables.filter(originalList, matchesWithRegex);
And to convert the iterable to a list, you can again use Guava:
ArrayList<String> resultList = Lists.newArrayList(iterable);
In java 8 you can do something like this using new stream API:
List<String> filterList(List<String> list, String regex) {
return list.stream().filter(s -> s.matches(regex)).collect(Collectors.toList());
}
In addition to the answer from Konstantin: Java 8 added Predicate
support to the Pattern
class via asPredicate
, which calls Matcher.find()
internally:
Pattern pattern = Pattern.compile("...");
List<String> matching = list.stream()
.filter(pattern.asPredicate())
.collect(Collectors.toList());
Pretty awesome!