Java Regex as Predicate using Pattern.compile() Method

Learn to compile regular expression into java.util.function.Predicate. This can be useful when you want to perform some operation on matched tokens.

Convert Regex to Predicate

I have list of emails with different domain and I want to perform some operation only on email ids with domain name “example.com”.

Now use Pattern.compile().asPredicate() method to get a predicate from compiled regular expression. This predicate can be used with lambda streams to apply it on each token into stream.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class RegexPredicateExample {
	public static void main(String[] args) {
		// Compile regex as predicate
		Predicate<String> emailFilter = Pattern
										.compile("^(.+)@example.com$")
										.asPredicate();

		// Input list
		List<String> emails = Arrays.asList("alex@example.com", "bob@yahoo.com", 
							"cat@google.com", "david@example.com");

		// Apply predicate filter
		List<String> desiredEmails = emails
									.stream()
									.filter(emailFilter)
									.collect(Collectors.<String>toList());

		// Now perform desired operation
		desiredEmails.forEach(System.out::println);
	}
}

Output:

alex@example.com
david@example.com

Using Regex using Pattern.matcher()

If you want to use good old Pattern.matcher(), then use below code template.

public static void main(String[] args) 
{
	
	Pattern pattern = Pattern.compile("^(.+)@example.com$");
	
	// Input list
	List<String> emails = Arrays.asList("alex@example.com", "bob@yahoo.com", 
						"cat@google.com", "david@example.com");
	 
	for(String email : emails)
	{
	    Matcher matcher = pattern.matcher(email);
	    
	    if(matcher.matches()) 
	    {
	    	System.out.println(email);
	    }
	}
}

Output:

alex@example.com
david@example.com

Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Java Regex as Predicate using Pattern.compile() Method”

  1. I ran both the class above and figured out that the transitional approach runs quite faster compared to predicate approach .
    I want to know why and where we should predicate ?

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.