Java 8 Predicate Example
Hello readers, this tutorial explains Java 8 predicate example, which has been newly introduced in the java.util.function
package. This package describes the Predicate’s usage with the help of multiple examples.
1. Introduction
java.util.function.Predicate
is the new functional interface defined in the java.util.function
package. The Predicate 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
or false
) needs to be returned.
Since Predicate 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 of java.util.function.Predicate
.
1 2 3 4 5 6 7 8 9 | package java.util.function; import java.util.Objects; @FunctionalInterface public interface Predicate<T> { boolean test(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 valueT
is the type of the input to the predicateboolean test(T t)
returnstrue
if the input argument matches the test condition, otherwise returnsfalse
Following are the default methods provided in the Predicate Functional Interface which enable developers to do various types of boolean operations such as AND, 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
and predicate2
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!
2.3 Project Creation
This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> 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.
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
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
1 2 3 4 5 6 7 | < project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" > < 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 the src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: 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
.
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
.
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 | package com.jcg.java; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class PredicateExamples { private static void print(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" ); } public static void main(String[] args) { /***** Example #1 - Predicate String *****/ Predicate<String> predicateString = s -> { return s.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 -> { return i > 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 = new ArrayList<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-> { return s.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.
4. Run the Application
To run the application, right-click on the PredicateExamples
class -> Run As -> Java Application
. Developers can debug the example and see what happens after every step!
5. Project Demo
The application shows the following logs as output for the PredicateExamples.java
. This following example shows how to use the test()
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.
You can download the full source code of this example here: Java 8 Predicate Example
Last updated on May 26th, 2020