Home » Core Java » Java 8 Predicate Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

Java 8 Predicate Example

Hello readers, this tutorial explains the functional interface Predicate 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.

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 value
  • T is the type of the input to the predicate
  • boolean test(T t) returns true if the input argument matches the test condition, otherwise returns false

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!

Fig. 1: 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 to File -> New -> Maven Project.

Fig. 2: 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.

Fig. 3: 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 a pom.xml file will be created. It will have the following code:

pom.xml

<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.

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

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!

Fig. 9: Run Application

Fig. 9: Run Application

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.

!! '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. Conclusion

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 whatever you were looking for.

7. Download the Eclipse Project

This was an example of Java Predicate for the beginners.

Download
You can download the full source code of this example here: JavaPredicateEx
(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

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 ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of