• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java Predicate Example – Functional Interface

December 7, 2020 by javainterviewpoint Leave a Comment

The Predicate Functional interface takes a single input and returns a boolean value. The predicate interface is located in java.util.function package. It has a Single Abstract Method (SAM) test(), which accepts the generic object type T and returns a boolean.

Java Predicate Example

Java Predicate Example

Whenever we are creating a Lambda Expression, which takes a single input and returns a boolean value based on a certain condition, then the Predicate can be used as a target for the lambda expression.

Methods in Predicate Interface

  1. boolean test(T t) – This method takes a single generic argument and returns true or false
  2. default Predicate<T> and(Predicate<? super T> other) – This is a default method, returns a composed predicate that by performing short-circuiting logical AND of current predicate and another predicate.
  3. default Predicate<T> or(Predicate<? super T> other) – This is also a default method, returns a composed predicate that by performing short-circuiting logical OR of current predicate and another predicate.
  4. default Predicate<T> negate() – This also a default method, returns a predicate after performing logical negation(!) on the current predicate.
  5. static <T> Predicate<T> isEqual(Object targetRef) – This static method returns a predicate which test the equality of the arguments passed.

1. Java Predicate test() method example

If we have a lambda expression that takes a single input and evaluates it based on a condition and returns true or false based on the evaluation, then the Predicate interface is a perfect choice.

Let’s build a predicate which checks whether the number passed is greater than 3 or not.

package com.javainterviewpoint;

import java.util.function.Predicate;

public class NumberChecker
{
   public static void main(String[] args)
   {
      Predicate checker = number -> number > 3;

      System.out.println("Is 2 greater than 3 ? " + checker.test(2));
      System.out.println("Is 8 greater than 3 ? " + checker.test(8));
   }
}

In the above code, we have created a Predicate checker, which checks for the given number is greater than 3 or not.

Predicate checker = number -> number > 3;

We can invoke the checker predicate by passing an integer argument to the test() method.

Output:

Is 2 greater than 3 ? false
Is 8 greater than 3 ? true

The Predicate is a perfect candidate for filtering the elements in a collection, the filter() method of the Stream takes a Predicate as its argument.

package com.javainterviewpoint;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class NumberFilter
{
   public static void main(String[] args)
   {
      List<Integer> numbers = Arrays.asList(12, 2, 4, 1, 2, 0, 9, 3, 5);
      Predicate checker = number -> number > 3;

      numbers.stream().filter(number -> checker.test(number))
            .forEach(System.out::println);
   }
}

The code snippet filters the numbers which are lesser than 3 and prints the numbers which are greater than 3.

Output:

12
4
9
5

The predicate can be used on custom objects as well. Let’s create a predicate that gives us the name of the Student with mark greater than 50.

Student.java

package com.javainterviewpoint;

public class Student
{
   private int id;
   private int mark;
   private String name;

   public Student()
   {
      super();
   }
   public Student(int id, int mark, String name)
   {
      super();
      this.id = id;
      this.mark = mark;
      this.name = name;
   }
   public int getId()
   {
      return id;
   }
   public void setId(int id)
   {
      this.id = id;
   }
   public int getMark()
   {
      return mark;
   }
   public void setMark(int mark)
   {
      this.mark = mark;
   }
   public String getName()
   {
      return name;
   }
   public void setName(String name)
   {
      this.name = name;
   }
}

StudentPredicate.java

package com.javainterviewpoint;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

public class StudentPredicate
{
   public static void main(String[] args)
   {
      List<Student> studentList = new ArrayList<Student>();

      studentList.add(new Student(1, 45, "Alice"));
      studentList.add(new Student(2, 65, "Bob"));
      studentList.add(new Student(3, 80, "Clair"));
      studentList.add(new Student(4, 20, "Dom"));

      Predicate markPredicate = mark -> mark > 50;

      System.out.println("** Student with marks greater than 50 **");
      studentList.stream()
            .filter(student -> markPredicate.test(student.getMark()))
            .forEach(student -> System.out.println(student.getName()));
   }
}

In the above code, we have created a simple predicate which checks whether the mark is greater than 50 or not.

Output:

** Student with marks greater than 50 **
Bob
Clair

2. Predicate interface and() method example

Let’s look into the above code where we checked whether the number is greater than 3. Suppose if we want the numbers which are greater than 3 but less than 10, then how do we achieve it?

We can use the and() method to chain the predicates, where one predicates whether the number is greater than 3, and the other predicate checks whether the number is less than 10.

package com.javainterviewpoint;

import java.util.function.Predicate;

public class NumberChecker
{
   public static void main(String[] args)
   {
      Predicate checker1 = number -> number > 3;
      Predicate checker2 = checker1.and(number -> number < 10);

      System.out.println("Does 1 satisfies the condition ? " + checker2.test(1));
      System.out.println("Does 7 satisfies the condition ? " + checker2.test(7));
      System.out.println("Does 11 satisfies the condition ? " + checker2.test(11));
   }
}

We have used the and() method to chain the checker1 and checker2 predicates; also note that the and() method performs short-circuiting logical AND operation, so only when checker1 is true it checks checker2.

Output:

Does 1 satisfies the condition ? false
Does 7 satisfies the condition ? true
Does 11 satisfies the condition ? false

3. Predicate interface or() method example

The or() methods also chain two predicates; the only difference is that it performs the short-circuiting logical OR operation.

Let’s chain the above predicate with the or() method and check the results.

package com.javainterviewpoint;

import java.util.function.Predicate;

public class NumberChecker
{
   public static void main(String[] args)
   {
      Predicate checker1 = number -> number > 3;
      Predicate checker2 = checker1.or(number -> number < 10);

      System.out.println("Does 1 satisfies the condition ? " + checker2.test(1));
      System.out.println("Does 7 satisfies the condition ? " + checker2.test(7));
      System.out.println("Does 11 satisfies the condition ? " + checker2.test(11));
   }
}

Output:

Does 1 satisfies the condition ? true
Does 7 satisfies the condition ? true
Does 11 satisfies the condition ? true

While using the and() method, the results are false, true, and false, whereas for the or() method, it is true, true, and true.

Since the or() method performs short-circuiting logical OR operation, only if checker1 is false, it checks checker2, and so the below condition will be checked.

  1. Since is 1 is less than 3, checker2 will be checked, and 1 is less than 10, so we get true.
  2. 7 is greater than 3, so we get true. checker2 will not be checked
  3. Similarly, 11 is greater than 3, so we will get true.

4. Predicate functional interface negate() method example

Suppose if we already have a predicate, and we want to perform a NOT operation on it, then we can use the negate() method.

Let’s take the checker1 predicate, which checks whether the number is greater than 3 or not. If we want the numbers less than 3, then we can call the negate() method on the checker1 predicate.

package com.javainterviewpoint;

import java.util.function.Predicate;

public class NumberChecker
{
   public static void main(String[] args)
   {
      Predicate checker1 = number -> number > 3;
      
      System.out.println("*** Checker 1 Predicate without negate**** ");
      System.out.println("Does 1 satisfies the condition ? " + checker1.test(1));
      System.out.println("Does 2 satisfies the condition ? " + checker1.test(2));
      System.out.println("Does 6 satisfies the condition ? " + checker1.test(6));
      
      Predicate checker1Negate = checker1.negate();
      
      System.out.println("*** Checker 1 Predicate with negate**** ");
      System.out.println("Does 1 satisfies the condition ? " + checker1Negate.test(1));
      System.out.println("Does 2 satisfies the condition ? " + checker1Negate.test(2));
      System.out.println("Does 6 satisfies the condition ? " + checker1Negate.test(6));
   }
}

Output:

*** Checker 1 Predicate without negate**** 
Does 1 satisfies the condition ? false
Does 2 satisfies the condition ? false
Does 6 satisfies the condition ? true
*** Checker 1 Predicate with negate**** 
Does 1 satisfies the condition ? true
Does 2 satisfies the condition ? true
Does 6 satisfies the condition ? false

We can see that the results get inversed when we negate.

5. Java Predicate isEqual() method example

The isEqual() method is a static method that checks whether the two arguments are equal or not.

package com.javainterviewpoint;

import java.util.function.Predicate;

public class IsEqualPredicate
{
   public static void main(String[] args)
   {
      Predicate helloPredicate = Predicate.isEqual("Hello");

      System.out.println(helloPredicate.test("Hello"));
      System.out.println(helloPredicate.test("Morning"));
   }
}

Output:

true
false

Happy Learning!!

Filed Under: Java Tagged With: Functional Interface, Java Predicate Example, Java Predicate Interface, Predicate, Predicate Example, Predicate Interface

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·