Java - Filtering List Entries by Regex

前端 未结 3 1729
孤街浪徒
孤街浪徒 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 which might be pretty useful for your case.

    static String regex = "yourRegex";
    
    Predicate matchesWithRegex = new Predicate() {
            @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 iterable = Iterables.filter(originalList, matchesWithRegex);
    

    And to convert the iterable to a list, you can again use Guava:

    ArrayList resultList = Lists.newArrayList(iterable);
    

提交回复
热议问题