Java Predicate Negate

Lets look at an example of a predicate that filters even numbers then we will use the same predicate to filter odd numbers

Getting started

While this tutorial maybe basic, until you learn what java 8 methods are available especially when calling the stream filter method, you might want to take the opposite of what predicate is set up for. Instead of rewriting the predicate, you can simply use the negate property that exist on the Predicate object. When making this method call, it will return a predicate that represents the logical negation of the predicate. So lets look at an example of a predicate that filters even numbers then we will use the same predicate to filter odd numbers. Also, be sure if your list contains null to remove null values otherwise you could run into a NullPointerException.

isEven Predicate

First lets write a predicate called isEven that can be passed to stream.filter and return even numbers.

List<Integer> myList = Arrays.asList(1, 2, 3, 4, 5);
Predicate<Integer> isEven = (x) -> x % 2 == 0;

myList.stream().filter(isEven).forEach(System.out::println);

Output

2
4

isOdd Predicate

If a requirement changes that states filter odd numbers, instead of creating a isOdd predicate we can simply call the negate() operation on the predicate to get the odd results. We can print stream in java 8 by passing the static println to the foreach.

List<Integer> myList = Arrays.asList(1, 2, 3, 4, 5);
Predicate<Integer> isEven = (x) -> x % 2 == 0;

myList.stream().filter(isEven.negate()).forEach(System.out::println);

Output

1
3
5

Guava negate

Just for reference, if you grew up using guava and com.google.common.base.Predicate this example looks slightly different. Instead of calling the negate method, you will need to call utility method Predicates.not passing in predicate which will evaluate to true if the given predicate evaluates to false.

com.google.common.base.Predicate<Integer> isEven = new com.google.common.base.Predicate<Integer>() {
    @Override
    public boolean apply(Integer input) {
        return input % 2 == 0;
    }
};

@Test
public void predicate_guava() {

    List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

    List<Integer> oddList = FluentIterable.from(numbers)
            .filter(Predicates.not(isEven)).toList();

    System.out.println(oddList);
}

Thanks for joining in today's level up, have a great day!