Java 8 — Predicate | Code Factory

Index Page : Link

Reference Link : Link

Donate : Link

  • A Predicate is a function with a single argument and returns boolean value.
  • To implement Predicate functions in Java, Oracle people introduced Predicate interface in 1.8 version (i.e. Predicate<T>).
  • Predicate interface present in java.util.function package.
  • It’s a functional interface and it contains only one method i.e., test()
  • As Predicate is a functional interface and hence it can refers Lambda (λ) Expression.

Converting normal method to predicate :

CE : incompatible types: String cannot be converted to Integer

Write a predicate to check the length of given string is greater than 3 or not :

write a predicate to check whether the given collection is empty or not :

Predicate Joining :

It’s possible to join predicates into a single predicate by using the following methods.

  1. and()
  2. or()
  3. negate()

These are exactly same as logical AND, OR, complement operators

Output :

Program to display names starts with ’N’ by using Predicate :

Output :

Predicate Example to remove null values and empty strings from the given array :

Output :

Program for User Authentication by using Predicate :

Output :

Employee Management Application :

Output :

Predicate interface isEqual() method :

  • To check whether the given element equal to element represented by Predicate or not.

Predicate Practice Bits :

(1) Which of the following abstract method present in Predicate interface?

(2) Which of the following is the static method present in Predicate interface?

(3) Which of the following default methods present in Predicate interface?

(4) Which of the following is Predicate interface declaration?

(5) Which of the following is valid Predicate to check whether the given Integer is divisible by 10 or not?

(6) Which of the following is valid regarding Predicate functional interface?

(7) Which of the following is valid Predicate to check whether the given user is admin or not?

(8) Consider the following Predicates

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store