Java - Filtering List Entries by Regex

前端 未结 3 1728
孤街浪徒
孤街浪徒 2020-12-29 07:42

My code looks like this:

List filterList(List list, String regex) {
  List result = new ArrayList();
         


        
相关标签:
3条回答
  • 2020-12-29 08:01

    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);
    
    0 讨论(0)
  • 2020-12-29 08:16

    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());
    }
    
    0 讨论(0)
  • 2020-12-29 08:20

    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!

    0 讨论(0)
提交回复
热议问题