Now, I want to introduce you some Java 8 Regex as Predicate examples. I make sure that you were ever in a situation in which you want to perform some operation to matched tokens. You can use Regex with Pattern.matcher() to resolve that issue but you can also do that using Regex as Predicate in Java 8.
Let’s begin.
Now, we’re considering the regular expression for validate email example
1 |
"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$" |
And the list of email address for testing as below
1 2 |
// Input list List<String> emails = Arrays.asList("@javabycode.com", "michael@.com", "test@google.com", "luk@javabycode.com"); |
1. Convert Regex to Predicate
You can compile regex as predicate and filter that predicate like below
1 2 3 4 5 |
Pattern pattern = Pattern.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"); // Compile regex as predicate // Apply predicate filter List<String> desiredEmails = emails.stream().filter(pattern.asPredicate()).collect(Collectors.<String>toList()); |
2. Using Regex with Lambda Expression
We also using Regex in lambda expression such as
1 2 3 |
Pattern pattern = Pattern.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"); //Using Regex with lambda expression List<String> desiredEmails1 = emails.stream().filter(p -> pattern.matcher(p).find()).collect(Collectors.<String>toList()); |
3. Using Regex with Predicate functional interface
Predicate is a functional interface, so you can implement the Predicate body
1 2 3 4 5 |
List<String> result2 = emails.stream().filter(new Predicate<String>() { public boolean test(String s) { return pattern.matcher(s).find(); } }).collect(Collectors.<String>toList()); |
Demo Program
Now we’re creating demo program for testing three above options
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class RegexAsPredicate { public static void main(String[] args) { // Input list List<String> emails = Arrays.asList("@javabycode.com", "michael@.com", "test@google.com", "luk@javabycode.com"); Pattern pattern = Pattern.compile("^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$"); // Compile regex as predicate // Apply predicate filter List<String> result = emails.stream().filter(pattern.asPredicate()).collect(Collectors.<String>toList()); List<String> result1 = emails.stream().filter(p -> pattern.matcher(p).find()) .collect(Collectors.<String>toList()); List<String> result2 = emails.stream().filter(new Predicate<String>() { public boolean test(String s) { return pattern.matcher(s).find(); } }).collect(Collectors.<String>toList()); // Now printing the result result.forEach(System.out::println); result1.forEach(System.out::println); result2.forEach(System.out::println); } } |
Output
That’s all about Java 8 Regex as Predicate examples.
References
Predicate (Java Platform SE 8 )
Pattern (Java Platform SE 8 )
Download the complete source code, click below
RegexAsPredicate.zip (296 downloads)