Java Predicate Explained [Practical Examples]


JAVA

Reviewer: Deepak Prasad

Introduction to Java Predicates

A predicate is an inline implementation of the functional interface java.util.function.Predicate<T>, which declares a single method named test(T t) that returns a boolean value. The implementation of this method should test its single argument of type T against a condition and returns true if the condition is fulfilled and false if not.

 

Imports to use Java predicate

The library used to implement predicates is the java.util.function.

java predicate

 

How to Use Java Predicates

To use predicates, the java.util.functions library is imported, the class in which predicates are used implements the class Predicate<T>, this class must have a test function that returns either true or false according to the logic. The example below shows how the predicate works.

This code returns false if the number is negative and returns true otherwise.

import java.util.function.*;
public class main {
    public static void main(String[] args) {

        // Create a predicate
        Predicate <Integer> negative = n -> (n < 0);

        // test the java predicate
        System.out.println(negative.test(-1));
    }
}

The output of the following code is :

true

 

Java Predicates with Lambda

The java predicates are mainly used for lambda expressions. A lambda expression in java is a block of code that takes certain parameters and returns a value, it is similar to nonvoid functions but the only difference is they don’t need a name and they can be directly used in the main function, they don’t need to be defined. The block of code below explains how java lambda expressions work.

import java.util.ArrayList;
public class main {

    // main function
    public static void main(String[] args) { 

        // arraylist
        ArrayList <Integer> numbers = new ArrayList <Integer> ();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);

        // java lambda expression
        // prints only numbers greater than 1
        numbers.forEach((n) -> {
            if (n > 1) System.out.println(n);
        });
    }

}

Output of this code is

2
3
4

As you can see, only the list numbers greater than 1 are shown. Similarly we can take parameters in lambda expressions.

Now we will see how java predicates simplify the lambda expressions. Predicate interface is normally used for lambda expressions, the code below will explain how:

import java.util.ArrayList;
import java.util.function.Predicate;
public class main {

    // main function
    public static void main(String[] args) {

        // implementation of java predicate using lambda expression
        Predicate <Integer> pred = n -> {

            // java predicate conditions
            if (n < 0) {
                System.out.println("negative");
                return false;
            } else {
                System.out.println("positive");
                return true;
            }
        };
        // test the java predicate by passing a value in the test function
        System.out.println(pred.test(10));
    }
}

The output of the following code is

positive
true

The same code implemented by the java predicate class is now implemented through lambda expressions, this way is much simpler.

 

The List removeIf(Predicate p) Function

The java List has a function removeIf, which removes an element from the list if the predicate condition satisfies, the code below will illustrate how it is used in list.

import java.util.ArrayList;
import java.util.function.Predicate;
public class main {

    // main function
    public static void main(String[] args) { 

        // arraylist
        ArrayList <Integer> numbers = new ArrayList <Integer> ();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);

        // java lambda expression
        // prints only numbers greater than 1
        Predicate <Integer> pred = n -> n == 1;
        numbers.removeIf(pred);
        System.out.println(numbers);
    }

}

The output of the code below is

[2, 3, 4]

In this code, a predicate is introduced which checks if number is equals to 1, and in the removeif condition we passed the predicate, so whenever the number 1 occurs in the list, it is removed, hence the list returned has no 1.

 

List Stream Filter Method

This method filter out a collection of objects using predicate

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class main {

    // main function
    public static void main(String[] args) { 

        // arraylist
        ArrayList <Integer> numbers = new ArrayList <Integer> ();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);

        // java lambda expression
        // prints only numbers greater than 1
        Predicate <Integer> pred = n -> n != 1;

        // java predicate filter method
        numbers.stream().filter(pred).collect(Collectors.toList()).forEach(System.out::print);
    }
}

The output of this code is

234

 

Multiple Conditions in Java Predicate

In java predicate, multiple conditions can be set using and (&&) and or(||) method. In the code below multiple conditions are set for java predicate.

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class main {

    // main function
    public static void main(String[] args) { 

        // arraylist
        ArrayList <Integer> numbers = new ArrayList <Integer> ();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);

        // java lambda expression
        //prints only numbers greater than 1
        Predicate <Integer> pred = n -> n != 1 && n != 2;

        // java predicate filter method    
        numbers.stream().filter(pred).collect(Collectors.toList()).forEach(System.out::print);
    }
}

The output of this code becomes

34

The condition specified is that the list can neither have 1 nor 2.

We can also use the and and or function of java predicate itself, for this we will have to make a separate predicate for each condition, like in the code below :

import java.util.ArrayList;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class main {

    // main function
    public static void main(String[] args) { 

        // arraylist
        ArrayList <Integer> numbers = new ArrayList <Integer> ();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);

        // java lambda expression
        // prints only numbers greater than 1
        Predicate <Integer> pred = n -> n != 1;

        // another java predicate for another conditoon
        Predicate <Integer> pred2 = n -> n != 2;

        // java filter method
        // use java predicate and method           
        numbers.stream().filter(pred.and(pred2)).collect(Collectors.toList()).forEach(System.out::print);

    }
}

Output of this code is :

23

Same as above, but we used java predicates and functions to implement multiple conditions.

 

List of predicates in Java

We can also implement a list of predicates in java , the code below demonstrates how

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class main {
    public static void main(String[] args) {

        // numbers list
        List <Integer> Numbers = List.of(1, 2, 3, 4, 5, 6, 6, 6, 7);

        // java predicate list
        Predicate <Integer> p1 = e -> e != 1;
        Predicate <Integer> p2 = e -> e != 2;
        Predicate <Integer> p3 = e -> e != 3;

        // made list
        List <Predicate <Integer>> prs = List.of(p1, p2, p3);

        // result
        List <Integer> result = Numbers.stream()
            .filter(prs.stream().reduce(x -> true, Predicate::and))
            .collect(Collectors.toList());
        result.forEach(System.out::println);
    }
}

The output of the following code is

4
5
6
6
6
7

All the list of code is implemented here.

 

Java Predicate negate function

This method returns the negation of the predicate, the code below shows how the negate method works

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

public class main {

    public static void main(String[] args) {

        // numbers list
        List <Integer> Numbers = List.of(1, 2, 3, 4, 5, 6, 6, 6, 7);

        // predicate list
        Predicate <Integer> p1 = e -> e != 1;
        Predicate <Integer> p2 = e -> e != 2;
        Predicate <Integer> p3 = e -> e != 3;

        // made list
        List < Predicate <Integer>> prs = List.of(p1, p2, p3);

        // result
        List <Integer> result = Numbers.stream()
            .filter(p1.negate())
            .collect(Collectors.toList());
        result.forEach(System.out::println);
    }
}

This code will return the logical negation of the predicate p1

The output is

1

 

Practice code

This code is to practice all the methods discussed above, dry run the code, and run it afterward

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class main {
    public static void main(String[] args) {

        // numbers list
        List <Integer> Numbers = List.of(1, 2, 3, 4, 5, 6, 6, 6, 7);

        // java predicate list
        Predicate <Integer> p1 = e -> e != 1;
        Predicate <Integer> p2 = e -> e != 2;
        Predicate <Integer> p3 = e -> e != 3;

        Numbers.stream().filter(p1.and(p2)).collect(Collectors.toList()).forEach(System.out::print);

        // made list
        List < Predicate < Integer >> prs = List.of(p1, p2, p3);

        // result
        List <Integer> result = Numbers.stream()
            .filter(prs.stream().reduce(x -> true, Predicate::and))
            .collect(Collectors.toList());
        result.forEach(System.out::println);
        List <Integer> result1 = Numbers.stream()
            .filter(p1.negate())
            .collect(Collectors.toList());
        result1.forEach(System.out::println);

    }

}

 

Conclusion

We have studied predicates, how to use them using the test method, then how to use predicates using java lambda expressions, furthermore we also discussed how multiple conditions can be implemented using predicates and how a list of predicates are used, we also learned about the negate function.

 

Further Reading

To further read about the Predicates click on the links below

Java Predicates
Predicates

 

Azka Iftikhar

Azka Iftikhar

She is proficient in multiple programming languages, including C++, GO, and Java, she brings a versatile skillset to tackle a wide array of challenges. Experienced Computer Scientist and Web Developer, she excels as a MERN Stack Expert. You can check her professional profile on GitHub which captures her experience and portfolio.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment