Predicate Interface is a part of the java.util.function package which is introduced in Java 8.  Predicate Negate returns the logical negation of the given predicate. In this post, we are going to see a few implementations of how to use it.

Predicate Negate in Java 8 with Examples...!!! Share on X

Example 1. with ArrayList

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PredicateInterface_Negate_with_ArrayList_Java8 {

    public static void main(String[] args) {
        List <Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        Predicate <Integer> isEven = i -> i % 2 == 0;

        Predicate <Integer> isOdd = isEven.negate();

        List <Integer> evenNumbers = list.stream().filter(isEven).collect(Collectors.toList());

        List <Integer> oddNumbers = list.stream().filter(isOdd).collect(Collectors.toList());

        System.out.println("Even Numbers:\n" + evenNumbers);
        System.out.println("\nOdd Numbers:\n" + oddNumbers);
    }

}

Example 2. using IntStream

package org.personal.samples;

import java.util.function.IntPredicate;
import java.util.stream.IntStream;

public class PredicateInterface_Negate_with_IntStream_Java8 {

    public static void main(String[] args) {

        IntPredicate isEven = i -> i % 2 == 0;

        IntPredicate isOdd = isEven.negate();

        System.out.println("Even Numbers:\n");
        IntStream.of(1, 2, 3, 4, 5).filter(isEven).forEach(System.out::println);

        System.out.println("\nOdd Numbers:\n");
        IntStream.of(1, 2, 3, 4, 5).filter(isOdd).forEach(System.out::println);

    }

}

It is quite a useful method and can help shorten the code. I hope the above examples could help you to get a better idea of how and where to use it.

Predicate Negate in Java 8 with Examples...!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts