Functional Interfaces: Predicate

Applies a test to an object and returns the result.

Overview

Examples

Filter a Collection using Collection.removeIf(Predicate):

Collection<Integer> data = new LinkedList<>(List.of(1, 1, 2, 3, 5, 8, 13));
data.removeIf((v) -> v % 2 == 0); // Remove even values.
// data contains [1, 1, 3, 5, 13]

Filter a Stream using Stream.filter(Predicate):

List<Integer> data = Stream.of(1, 1, 2, 3, 5, 8, 13)
    .filter((v) -> v % 2 == 1) // Preserve odd values.
    .collect(Collectors.toList());
// data contains [1, 1, 3, 5, 13]

Note that the sense of the predicate is reversed in the two uses shown above: Collection.removeIf(Predicate) removes an item from the collection if (and only if) the predicate evaluates to true for that item; Stream.filter(Predicate) preserves an item in the stream if (and only if) the predicate evaluates to true for that item.