The Predicate functional interface from the java.util.function package that was introduced in Java 8 contains a default method called negate() which returns a logical negation of the predicate function test().
default Predicate<T> negate()
Let's take a look at a few simple examples with negate() as lambda expressions.
Example 1: Check if Number is Not Even using negate()
package org.code2care.examples;
import java.util.function.Predicate;
/**
*
* Java 8 Predicate negate() Example
* version: v1.0
* Author: Code2care.org
* Date: 11 Oct 2023
*
*/
public class PredicateNegateExample {
public static void main(String... args) {
Predicate<Integer> isEven = num -> num % 2 == 0;
//Using negate()
Predicate<Integer> isNotEven = isEven.negate();
int no1 = 12;
int no2 = 19;
String result1 = isEven.test(no1) ? "even" : "not even";
String result2 = isNotEven.test(no2) ? "not even" : "even";
System.out.println(no1 + " is " + result1 + ".");
System.out.println(no2 + " is " + result2 + ".");
}
}
Output:
Example 2: Products not on Sale
package org.code2care.examples;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
class Item {
private String deviceName;
private boolean onSale;
public Item(String deviceName, boolean onSale) {
this.deviceName = deviceName;
this.onSale = onSale;
}
public boolean isOnSale() {
return onSale;
}
public String getName() {
return deviceName;
}
}
public class ShoppingCartExample {
public static void main(String[] args) {
List<Item> applePC = new ArrayList<>();
applePC.add(new Item("Macbook", false));
applePC.add(new Item("Mac Mini", true));
applePC.add(new Item("iMac", false));
applePC.add(new Item("Mac Studio", true));
Predicate<Item> isOnSale = Item::isOnSale;
//Negate
Predicate<Item> isNotOnSale = isOnSale.negate();
applePC.stream()
.filter(isNotOnSale)
.forEach(item -> System.out.println(item.getName() + " is not on sale."));
}
}
Output:

Read More:
- https://docs.oracle.com/javase/8/docs/api/java/util/function/Predicate.html#negate
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!