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 “”.

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;

public class RegexPredicateExample {
	public static void main(String[] args) {
		// Compile regex as predicate
		Predicate<String> emailFilter = Pattern

		// Input list
		List<String> emails = Arrays.asList("", "", 
							"", "");

		// Apply predicate filter
		List<String> desiredEmails = emails

		// Now perform desired operation


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("^(.+)$");
	// Input list
	List<String> emails = Arrays.asList("", "", 
						"", "");
	for(String email : emails)
	    Matcher matcher = pattern.matcher(email);


Drop me your questions in comments section.

Happy Learning !!


Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode