Java示例中的模式asPredicate()方法
java.util.function包的Predicate接口可用作lambda表达式的目标。此接口的测试方法接受一个值,并用谓词对象的当前值对其进行验证。如果有匹配项,则此方法返回true,否则返回false。
java.util.regex.Pattern类的asPredicate()方法返回一个Predicate对象,该对象可以将字符串与正则表达式匹配,使用该正则表达式可以编译当前的Pattern对象。
例子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"); } } }
输出结果
Enter input string Nhooo Number of matches: 3
例子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); }); } }
输出结果
Match found Java Match found JavaFX Match found JavaScript