Java – 由Regex过滤列表条目

我的代码如下所示:

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

它返回一个列表,其中只包含与regex匹配的条目。 我想知道是否有这样的内置function:

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

谷歌的Java库(Guava)有一个接口Predicate ,它可能对你的情况非常有用。

 static String regex = "yourRegex"; Predicate matchesWithRegex = new Predicate() { @Override public boolean apply(String str) { return str.matches(regex); } }; 

您可以定义类似上面的谓词,然后使用单行代码根据此谓词过滤列表:

 Iterable iterable = Iterables.filter(originalList, matchesWithRegex); 

要将iterable转换为列表,您可以再次使用Guava:

 ArrayList resultList = Lists.newArrayList(iterable); 

除了Konstantin的答案之外:Java 8通过asPredicatePattern类中添加了Predicate支持,它在内部调用了Matcher.find()

 Pattern pattern = Pattern.compile("..."); List matching = list.stream() .filter(pattern.asPredicate()) .collect(Collectors.toList()); 

真棒!

在java 8中,您可以使用新的流API执行以下操作 :

 List filterList(List list, String regex) { return list.stream().filter(s -> s.matches(regex)).collect(Collectors.toList()); }