Java Pattern asMatchPredicate()

In this guide, you will learn about the Pattern asMatchPredicate() method in Java programming and how to use it with an example.

1. Pattern asMatchPredicate() Method Overview

Definition:

The asMatchPredicate() method is part of the Pattern class in Java. It returns a predicate that tests if the given string matches the pattern. This method is particularly useful for filtering and stream operations, allowing for concise syntax when checking if strings match a particular pattern.

Syntax:

Predicate<String> asMatchPredicate()

Parameters:

This method does not take any parameters.

Key Points:

- The method is part of Java 11 and later.

- It returns a Predicate that can be used with stream operations such as filter.

- The returned predicate uses the Pattern.matcher(input).matches() to evaluate the string.

2. Pattern asMatchPredicate() Method Example

import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Stream;

public class AsMatchPredicateExample {

    public static void main(String[] args) {
        // Creating a pattern for a simple date format: YYYY-MM-DD
        Pattern datePattern = Pattern.compile("\\d{4}-\\d{2}-\\d{2}");

        // Getting the match predicate from the pattern
        Predicate<String> dateMatcher = datePattern.asMatchPredicate();

        // Creating a stream of date strings and filtering them using the match predicate
        Stream.of("2023-09-27", "12-34-5678", "2021-05-15", "abcd-efgh-ijkl")
              .filter(dateMatcher)
              .forEach(System.out::println);
    }
}

Output:

2023-09-27
2021-05-15

Explanation:

In this example, a pattern for a simple date format "YYYY-MM-DD" is compiled, and the asMatchPredicate() method is used to obtain a Predicate<String>

A stream of strings representing various date and non-date values is created. The filter() operation on the stream, utilizing the obtained predicate, filters the stream, allowing only the strings that match the date pattern to be printed. The output shows only the strings that match the pattern.

Comments