English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
java.util.functionof the 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.Patternof the classasPredicate()The method returns a Predicate object that can match a string with a regular expression, using which the current Pattern object can be compiled.
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("Entrez une chaîne d'entrée"); String input = sc.nextLine(); //Expression régulière pour trouver des chiffres String regex = "[t]"; //Compilation de l'expression régulière Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE); //Conversion de l'expression régulière en prédicat Predicate<String> predicate = pattern.asPredicate(); //Testing the predicate with the input string boolean result = predicate.test(input); if(result) { System.out.println("Correspondance trouvée"); } else { System.out.print("Aucune correspondance trouvée"); } } }
Résultat de la sortie
Entrez une chaîne d'entrée w3codebox Nombre de 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")); //Expression régulière pour trouver des chiffres String regex = "[J]"; //Compilation de l'expression régulière Pattern pattern = Pattern.compile(regex); //Conversion de l'expression régulière en prédicat Predicate<String> predicate = pattern.asPredicate(); list.forEach(n -> { if (predicate.test(n)) System.out.println("Match trouvé "+n); }); } }
Résultat de la sortie
Match trouvé Java Match trouvé JavaFX Match trouvé JavaScript