Core Java

Java 8 Predicate Example

Photo of YatinYatinJanuary 9th, 2018Last Updated: November 25th, 2020
0 360 5 minutes read

Hello readers, this tutorial explains Java 8 predicate example, which has been newly introduced in thejava.util.function package. This package describes thePredicate’s usage with the help of multiple examples.

1. Introduction

java.util.function.Predicate is the newfunctional interface defined in thejava.util.function package. ThePredicate is used in all the contexts where an object needs to be evaluated for a given test condition and a boolean value (i.e.true orfalse) needs to be returned.

 
SincePredicate is a functional interface, hence it can be used as the assignment target for the lambda expressions or the method references.

Here is a simple source code ofjava.util.function.Predicate.

1
2
3
4
5
6
7
8
9
packagejava.util.function;
     
importjava.util.Objects;
     
@FunctionalInterface
publicinterfacePredicate<T> {
    booleantest(T t);
    /**** Rest Code Goes Here *****/
}

Where:

  • boolean test(T t): It is the abstract method which will define the signature of the lambda expression or the method reference and can be assigned to a target of type predicate. This abstract method will always return a Boolean value
  • T is the type of the input to the predicate
  • boolean test(T t) returnstrue if the input argument matches the test condition, otherwise returnsfalse

Following are the default methods provided in thePredicate Functional Interface which enable developers to do various types of boolean operations such asAND,OR,NOT (i.e. Negate) with different instances of Predicate.

  • and(): It does the logical ‘AND ‘ of the predicate on which it is called with another predicate. For e.g.:predicate1.and(predicate2)
  • or(): It does the logical ‘OR ‘ of the predicate on which it is called with another predicate. For e.g.:predicate1.or(predicate2)
  • negate(): It does the boolean ‘negation’ of the predicate on which it is invoked. For e.g.:predicate1.negate()

Where,predicate1 andpredicate2 are instances of Predicate interface or Lambda Expression or the Method References. Now, open up the Eclipse Ide and let’s see a few examples of Predicates in Java!

2. Java 8 Predicate Example

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Java Predicate - Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go toFile -> New -> Maven Project.

Java Predicate - Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Java Predicate - Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default:0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and apom.xml file will be created. It will have the following code:

pom.xml

1
2
3
4
5
6
7
    <modelVersion>4.0.0</modelVersion>
    <groupId>JavaPredicateEx</groupId>
    <artifactId>JavaPredicateEx</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Java Class Creation

Let’s create the required Java files. Right-click on thesrc/main/java folder,New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as:com.jcg.java.

Fig. 6: Java Package Name (com.jcg.java)
Fig. 6: Java Package Name (com.jcg.java)

Once the package is created in the application, we will need to create the implementation class to illustrate the Java 8 Predicate examples. Right-click on the newly created package:New -> Class.

Fig. 7: Java Class Creation
Fig. 7: Java Class Creation

A new pop window will open and enter the file name as:PredicateExamples. The utility class will be created inside the package:com.jcg.java.

Fig. 8: Java Class (PredicateExamples.java)
Fig. 8: Java Class (PredicateExamples.java)

3.2.1 Implementation of Predicate Class

To illustrate the Predicate’s usage with the help of multiple examples, developers will have to use ‘ JDK 1.8 ‘. Let’s see the simple code snippet that follows this implementation.

PredicateExamples.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
packagecom.jcg.java;
 
importjava.util.ArrayList;
importjava.util.List;
importjava.util.function.Predicate;
 
publicclassPredicateExamples {
 
    privatestaticvoidprint(List<String> users, Predicate<String> empPredicate) {
        System.out.println("!! 'Predicate List' Output !!");
        for(String name : users) {
            if(empPredicate.test(name))
                System.out.println(name);
        }
 
        System.out.println("\n");
    }
 
    publicstaticvoidmain(String[] args) {
 
        /***** Example #1 - Predicate String *****/
        Predicate<String> predicateString = s -> {
            returns.equals("Java Code Geek");
        };
 
        System.out.println("!! 'Predicate String' Output !!");
        System.out.println(predicateString.test("Java Code Geek"));
        System.out.println(predicateString.test("Java Geek") +"\n");
 
        /***** Example #2 - Predicate Integer *****/
        Predicate<Integer> predicateInt = i -> {
            returni >0;
        };
 
        System.out.println("!! 'Predicate Integer' Output !!");
        System.out.println(predicateInt.test(10));
        System.out.println(predicateInt.test(-10) +"\n");
 
        /***** Example #3 - Predicate List *****/
        List<String> users =newArrayList<String>();      
        users.add("Bob");
        users.add("Jane");
        users.add("Jordi");
        print(users, user -> user.startsWith("J"));
 
        /***** Example #4 - Predicate Default Methods *****/
        Predicate<String> predicate = s-> {
            returns.equals("Java");
        };
 
        /** (4a) - AND Logical Operation **/ 
        Predicate<String> predicateAnd = predicate.and(s -> s.length() >3);
        System.out.println("!! 'Predicate Logical And' Output !!");
        System.out.println(predicateAnd.test("Java") +"\n");
 
        /** (4b) - OR Logical Operation **/
        Predicate<String> predicateOr = predicate.or(s -> s.length() ==10);
        System.out.println("!! 'Predicate Logical Or' Output !!");
        System.out.println(predicateOr.test("Java") +"\n");
 
        /** (4c) - NEGATE Logical Operation **/
        Predicate<String> predicateNegate = predicate.negate();
        System.out.println("!! 'Predicate Logical Negate' Output !!");
        System.out.println(predicateNegate.test("Java") +"\n");
    }
}

Do remember, developers will have to use the ‘JDK 1.8 ‘ dependency for implementing the Predicate’s usage in their applications.

Want to be a Java 8 Ninja ?
Subscribe to our newsletter and download the Java 8 FeaturesUltimateGuideright now!
In order to get you up to speed with the major Java 8 release, we have compiled a kick-ass guide with all the new features and goodies! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

4. Run the Application

To run the application, right-click on thePredicateExamples class-> Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application
Fig. 9: Run Application

5. Project Demo

The application shows the following logs as output for thePredicateExamples.java. This following example shows how to use thetest() method of the Predicate interface.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
!!'Predicate String'Output !!
true
false
 
!!'Predicate Integer'Output !!
true
false
 
!!'Predicate List'Output !!
Jane
Jordi
 
!!'Predicate Logical And'Output !!
true
 
!!'Predicate Logical Or'Output !!
true
 
!!'Predicate Logical Negate'Output !!
false

That’s all for this post. Happy Learning!!

6. Summary

That’s all for Java 8 Predicate interface and developers can use it to check whether a lambda expression condition is true or false. I hope this article served you with whatever you were looking for.

7. Download the Eclipse Project

This was an example of Java Predicate for beginners.

Download
You can download the full source code of this example here:Java 8 Predicate Example

Last updated on May 26th, 2020

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of YatinYatinJanuary 9th, 2018Last Updated: November 25th, 2020
0 360 5 minutes read
Photo of Yatin

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.