Java Predicate Negate Example

Predicate negate returns a predicate that represents the logical negation of the given predicate. The negate predicate returns all the elements from stream which were filtered out by original predicate.

1. Java predicate negate() method

The Predicate.negate() method returns the logical negation of existing predicate.

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

public class Main 
{
	public static void main(String[] args) 
	{
		List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
		
		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(evenNumbers);
		System.out.println(oddNumbers);
	}
}

Program output.

[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

2. Java predicate not() method

In Java 11, Predicate class has new method not(). It returns a predicate that is the negation of the supplied predicate. This is accomplished by returning result of the calling predicate.negate().

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

public class Main 
{
	public static void main(String[] args) 
	{
		List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
		
		Predicate<Integer> isEven = i -> i % 2 == 0;
		
		Predicate<Integer> isOdd = Predicate.not( isEven );

		List<Integer> evenNumbers = list.stream()
					.filter(isEven)
					.collect(Collectors.toList());
		
		List<Integer> oddNumbers = list.stream()
				.filter(isOdd)
				.collect(Collectors.toList());
		
		System.out.println(evenNumbers);
		System.out.println(oddNumbers);
	}
}

Program output.

[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

Drop me your questions related to java stream predicate negate examples.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.