Predicate in java 8

If you want to learn java 8 or complete features of Java 8, you need to understand the basic interfaces. In this topic, we will discuss one of them and that is the java predicate and predicate in java 8. Most programmer doesn’t know how to with java predicate or java 8 predicate. Here we will see how to use it and discuss the java 8 predicate example also.

Here is the table content of the article will we will cover this topic.
1. What is the Predicate in Java?
2. How to use the Predicate interface?
3. Let’s discuss Predicate with the user-defined class?
4. Let’s discuss Predicate with Collection?
5. Advantages of Predicate?

What is the Predicate in Java 8?

In Java 8 Predicate interface is defined in the java.util.function package. It contains one abstract method that is called test() method. This interface provides functionality to test/evaluate any condition.

This interface is used in a lambda expression and method reference to evaluate the condition.

@FunctionalInterface
public interface Predicate<T> 
{
	// Body of Interface
}

Where T, The type of input of Predicate. Basically, it is a data type for eg: String, Integer.
boolean test(T t) method: This method is used to test the given input with the predicate. Its return type is boolean.
It returns true if the given argument matched with the predicate otherwise returns false.

boolean test(T t);

This interface contains a few extra methods but since they all come with a default implementation, you do not have to implement these extra methods.

java predicate

How to use the Predicate interface in java 8?

First of all, we will see how to use the Java 8 Predicate interface without a lambda expression.

import java.util.function.Predicate;
public class ExampleOfPredicateWithoutLambda 
{
	public static void main(String arg[])
	{
		String stringOne = "Hello";
		Predicate<String> predicate = new Predicate<String>() {
			@Override
			public boolean test(String stringTwo) 
			{
				return stringOne.equals(stringTwo);
			}
		};
		System.out.println("It test the given string with predicate: ");
		System.out.println(predicate.test("Hi"));
		System.out.println(predicate.test("Hello"));
	}
}

Output: It test the given string with predicate: false
true

Now, we will see how you can use the Predicate interface with a lambda expression:

import java.util.function.Predicate;
public class ExampleOfPredicateWithLambda 
{
	public static void main(String[] args) 
	{
		// Creating predicate by use of lambda expression
		Predicate<String> predicate = (stringOne) -> (stringOne.equals("Hello"));
		System.out.println("Is these Strings are equal = "+predicate.test("Hi"));
		System.out.println("Is these Strings are equal = "+predicate.test("Hello"));
	}
}

Output: Is these Strings are equal = false
Is these Strings are equal = true

Let’s discuss Predicate with user-defined class

public class Student 
{
	int rollNo;
	String className;
	String name;
	public Student(int rollNo, String className, String name) 
	{
		this.rollNo = rollNo;
		this.className = className;
		this.name = name;
	}
	public int getRollNo() 
	{
		return rollNo;
	}
	public void setRollNo(int rollNo) 
	{
		this.rollNo = rollNo;
	}
	public String getClassName() 
	{
		return className;
	}
	public void setClassName(String className) 
	{
		this.className = className;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
import java.util.function.Predicate;
public class ExampleOfPredicateForStudent 
{
	public static void main(String[] args) 
	{
		// Adding data of Student
		Student studentOne =  new Student(1, "MCA", "Ram");
		Student studentTwo =  new Student(2, "MSC", "Sham");
		Predicate<Student> predicate = (student) -> (student.getRollNo() == 2);
		System.out.println("Is student rollNo is 2 = "+predicate.test(studentOne));
		System.out.println("Is student rollNo is 2 = "+predicate.test(studentTwo));
	}
}

Output: Is student rollNo is 2 = false
Is student rollNo is 2 = true

Let’s discuss Predicate with Collection

public class Book 
{
	int bookId;
	String name;
	String authorName;
	public Book(int bookId, String name, String authorName) 
	{
		this.bookId = bookId;
		this.name = name;
		this.authorName = authorName;
	}
	public int getBookId() 
	{
		return bookId;
	}
	public void setBookId(int bookId) 
	{
		this.bookId = bookId;
	}
	public String getName() 
	{
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAuthorName() {
		return authorName;
	}
	public void setAuthorName(String authorName) {
		this.authorName = authorName;
	}
}
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class ExampleOfPredicateWithCollection 
{
	public static void main(String[] args) 
	{
		Book bookOne = new Book(1, "ABC", "shiva");
		Book bookTwo = new Book(5, "DEF", "RAMA");
		Book bookThree = new Book(8, "GHI", "Krishna");
		List<Book> books = new ArrayList<Book>();
		books.add(bookOne);
		books.add(bookTwo);
		books.add(bookThree);
		Predicate<Book> predicate = (book) -> (book.getBookId() >= 5);
		books = books.stream().filter(predicate).collect(Collectors.<Book>toList());
		for(Book book : books)
			System.out.println("BookId = "+ book.getBookId());
		}		
}

Output: BookId = 5
BookId = 8

You see in the above example, we created Predicate and used it in a filter.  The filter method of Stream takes Predicate as an argument.

Advantage of Predicate

1. By use of Java Predicate, you can move the conditional code in one place.
2. It improves code maintenance because if you want to make any change in condition then you have to make it in a central place.

Frequently Asked Questions about Predicate in Java 8

What is the Predicate interface in Java 8?

The Predicate interface is defined in the java.util.function package. It contains one abstract method, test(), and provides functionality to test or evaluate a condition. It is commonly used with lambda expressions and method references.

Which method does the Predicate interface declare?

The Predicate interface declares the boolean test(T t) method. It returns true if the given argument matches the predicate, otherwise it returns false.

Do I have to implement all the methods of Predicate?

No. The interface contains a few extra methods, but they all come with a default implementation, so you do not have to implement these extra methods.

Can Predicate be used with a user-defined class?

Yes. As shown in the article, you can create a Predicate<Student> and test a condition such as student.getRollNo() == 2 against instances of your own class.

How is Predicate used with a Collection?

Predicate can be passed to the filter method of a Stream. In the article's example, a Predicate<Book> is used with books.stream().filter(predicate) to keep only the books that match the condition.

What are the advantages of using Predicate?

By using a Java Predicate you can move the conditional code into one place, and code maintenance improves because any change to the condition only has to be made in that central place.

7 thoughts on “Predicate in java 8”

  1. Well I really liked reading it. This post provided by you is very helpful for correct planning.

    Reply
  2. This is a interesting post by the way. I am going to go ahead and bookmark this article for my sister to read later on tonight. Keep up the good quality work.

    Reply
  3. Hello 🙂 Your blog looks good. have a nice day. the blog was absolutely fantastic!

    Reply
  4. WONDERFUL Post.thanks for share..more wait .. 😉

    Reply
  5. That was stimulating . I like your style that you put into your writing . Please do move forward with more like this.

    Reply
  6. Wonderful tutorials. Was forced to bookmark the site.

    Reply
  7. The dominant theme in the foyer is medievalism with a life-sized knight in shining armor guarding the large double doors, and an equally threatening armored warhorse peeking around the corner.

    Reply

Leave a Comment