อินเตอร์เฟซ Predicate ของแพ็กเกจ java.util.function ใช้เป็น target สำหรับ lambda expressions เมธอด test ของอินเตอร์เฟซนี้รับค่าและ validate กับค่าปัจจุบันของ Predicate object เมธอดนี้คืนค่า true ในกรณีของ match มิฉะนั้น false
เมธอด asPredicate() ของคลาส java.util.regex.Pattern คืนค่า Predicate object ซึ่งสามารถจับคู่สตริงกับ regular expression ที่ใช้คอมไพล์ Pattern object ปัจจุบัน
ตัวอย่างที่ 1: ใช้ Predicate กับ regex [t] case-insensitive
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.regex.Pattern;
public class AsPredicateExample {
public static void main(String args[]) {
// อ่านค่าสตริง
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string");
String input = sc.nextLine();
// Regular expression to find digits
String regex = "[t]";
// คอมไพล์ regular expression
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
// แปลง regular expression เป็น predicate
Predicate<String> predicate = pattern.asPredicate();
// ทดสอบ predicate กับสตริงอินพุต
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
ตัวอย่างที่ 2: ใช้ Predicate กับ ArrayList
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]";
// คอมไพล์ regular expression
Pattern pattern = Pattern.compile(regex);
// แปลง regular expression เป็น 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