Predicate and Composition
Compose boolean tests.
What Predicate Does
Predicate<T> takes a value and returns a boolean.
- Its method is
boolean test(T t). - It models a yes/no condition.
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<Integer> isEven = n -> n % 2 == 0;
System.out.println(isEven.test(4));
System.out.println(isEven.test(5));
}
}Predicate in filter
Stream.filter takes a Predicate and keeps only matching elements.
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Integer> nums = List.of(1, 2, 3, 4, 5, 6);
List<Integer> evens = nums.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evens);
}
}All lessons in this course
- Function and BiFunction
- Supplier and Consumer
- Predicate and Composition
- Custom Functional Interfaces