English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
java.util.functionThe packagePredicateThe interface can be used as the target of a lambda expression. The test method of this interface accepts a value and validates it with the current value of the predicate object. If there is a match, this method returns true, otherwise it returns false.
java.util.regex.PatternThe classasPredicate()The method returns a Predicate object that can match a string with a regular expression, and the current Pattern object can be compiled using this regular expression.
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 Result
Enter input string w3codebox Number of matches: 3
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 Result
Match found Java Match found JavaFX Match found JavaScript