Java 8: Predicate negate() default Function Example


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:

12 is even.
19 is not even.


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:

Macbook is not on sale.
iMac is not on sale.


negate() default function Predicate

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap