Benjy Kessler
Benjy Kessler

Reputation: 7656

Java - Filtering List Entries by Regex

My code looks like this:

List<String> filterList(List<String> list, String regex) {
  List<String> result = new ArrayList<String>();
  for (String entry : list) {
    if (entry.matches(regex)) {
      result.add(entry);
    }
  }
  return result;
}

It returns a list that contains only those entries that match the regex. I was wondering if there was a built in function for this along the lines of:

List<String> filterList(List<String> list, String regex) {
  List<String> result = new ArrayList<String>();
  result.addAll(list, regex);
  return result;
}

Upvotes: 23

Views: 55215

Answers (3)

scheffield
scheffield

Reputation: 6787

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!

Upvotes: 90

Juvanis
Juvanis

Reputation: 25950

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);

Upvotes: 4

Konstantin V. Salikhov
Konstantin V. Salikhov

Reputation: 4653

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());
}

Upvotes: 28

Related Questions