Filtering a list of tokens using the asPredicate() method

As noted in the preceding table, the asPredicate() method creates a predicate that can be used to match an input string. Let's look at an example code listing to understand this method better:

package example.regex; 

import java.util.List;
import java.util.stream.*;
import java.util.regex.*;

public class AsPredicateExample
{
public static void main(String[] args)
{
final String[] monthsArr =
{"10", "0", "05", "09", "12", "15", "00", "-1", "100"};

final Pattern validMonthPattern =
Pattern.compile("^(?:0?[1-9]|1[00-2])$");

List<String> filteredMonths = Stream.of(monthsArr)
.filter(validMonthPattern.asPredicate())
.collect(Collectors.toList());

System.out.println(filteredMonths);
}
}

This code has a list of month numbers as an array of String. The valid months are between 1 and 12 with an optional 0 before the single-digit months.

We use the following regex pattern for a valid month number:

 ^(?:0?[1-9]|1[00-2])$ 

We use the return value of the asPredicate() method to filter the stream of string array containing all the input month values.

After compiling and running, the preceding code will print the following output, which is a filtered list from the original list containing all the valid month numbers:

[10, 05, 09, 12] 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.131.212