What is the usage of Predicate in Java?
In Java, a Predicate is a functional interface that takes an input parameter and returns a boolean value. It is typically used for filtering or selecting elements in a collection. The Predicate interface contains an abstract method called test, which is used to define the condition for evaluation. Different filtering conditions can be defined by implementing the Predicate interface, and the test method can be called to determine if the input parameter meets the condition.
For example, you can use a Predicate to filter even elements in a list of integers.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Predicate<Integer> isEven = num -> num % 2 == 0;
List<Integer> evenNumbers = numbers.stream()
.filter(isEven)
.collect(Collectors.toList());
System.out.println(evenNumbers); // 输出 [2, 4, 6, 8, 10]
In the example above, we defined a Predicate implementation called isEven to determine if an integer is even, then used the filter method to select the even elements from the list and collect them into a new list. This achieves the operation of filtering elements in a collection. The Predicate interface provides many convenient methods to implement complex filtering conditions, which can be flexibly applied in various scenarios.