Pattern asPredicate() method in Java with examples

JavaObject Oriented ProgrammingProgramming

The Predicate interface of the java.util.function package can be used as a target for lambda expressions. The test method of this interface accepts a value ad validates it with the current value of the Predicate object. This method returns true in-case of a match, else false.

The asPredicate() method of the java.util.regex.Pattern class returns a Predicate object which can match a string with the regular expression using which the current Pattern object was compiled.

Example 1

import java.util.Scanner;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class AsPredicateExample {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find digits
      String regex = "[t]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
      //Converting the regular expression to predicate
      Predicate<String> predicate = pattern.asPredicate();
      //Testing the predicate with the input string
      boolean result = predicate.test(input);
      if(result) {
         System.out.println("Match found");
      } else {
         System.out.print("Match not found");
      }
   }
}

Output

Enter input string
Tutorialspoint
Number of matches: 3

Example 2

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class AsPredicateExample {
   public static void main( String args[] ) {
      ArrayList<String> list = new ArrayList<String>();
      list.addAll(Arrays.asList("Java", "JavaFX", "Hbase", "JavaScript"));
      //Regular expression to find digits
      String regex = "[J]";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Converting the regular expression to predicate
      Predicate<String> predicate = pattern.asPredicate();
      list.forEach(n -> { if (predicate.test(n)) System.out.println("Match found "+n); });
   }
}

Output

Match found Java
Match found JavaFX
Match found JavaScript
raja
Published on 20-Nov-2019 06:22:38
Advertisements