October 3, 2022

Predicate Functional Interface Java Examples

In this post we’ll see examples of java.util.function.Predicate functional interface.

Methods in Predicate interface

Predicate functional interface represents a boolean valued function returning either true or false. Abstract method in this functional interface is-

boolean test(T t)- This method evaluates the predicate on the passed argument and returns either true or false based on whether the input argument matches the predicate or not.

If you are writing a Lambda expression that takes single argument and uses that argument to evaluate a condition that returns true or false then that lambda expression can be written as an implementation of Predicate built-in functional interface.

Apart from the test() abstract method Predicate interface has following default and static methods.

  • and(Predicate<? super T> other)- It is a default interface method that returns a composed predicate representing a short-circuiting logical AND of this predicate and another. First the calling Predicate is evaluated if that is false then the predicate passed as argument is not even evaluated.
  • or(Predicate<? super T> other)- It is a default method that returns a composed predicate representing a short-circuiting logical OR of this predicate and another. In the composed predicate first the calling Predicate is evaluated if that is true then the predicate passed as argument is not even evaluated.
  • negate()- It is a default method that returns a predicate representing the logical negation of this predicate.
  • isEqual(Object targetRef)- It is a static interface method returning a predicate that tests if two arguments are equal according to Objects.equals(Object, Object).

Predicate interface test() method example

1. A simple implementation that checks if the passed argument is greater than 10 or not.

import java.util.function.Predicate;

public class PredicateExample {
  public static void main(String[] args) {
    Predicate<Integer> predicate = (i) -> i > 10;
    
    boolean val = predicate.test(8);
    System.out.println("val- " + val);
    
    val = predicate.test(15);
    System.out.println("val- " + val);
  }
}
Output
val- false
val- true

In the example; statement- Predicate predicate = (i) -> i > 10; is the implementation of Predicate interface as a lambda expression.

When predicate.test() method is called Java can infer from the context that lambda expression is the implementation of test() method.

2. In this example there is a method that takes two arguments; a Predicate and a List. From the passed list those elements that pass the predicate are added in another list.

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

public class PredicateExample {	
  public static void main(String[] args) {
    List<Integer> myList = new ArrayList<Integer>();
    myList.add(20);
    myList.add(60);
    myList.add(40);
    myList.add(80);
            
    Collection<Integer> values = filter(n -> n > 50, myList);                
    System.out.println("Values in new list " + values);
  }
	
  public static <T> Collection<T> filter(Predicate<T> predicate, Collection<T> listItems) {
    Collection<T> newList = new ArrayList<T>();
    for(T item: listItems) {
      if(predicate.test(item)) {
        newList.add(item);
      }
    }
    return newList;
  }
}
Output
Values in new list [60, 80]

Predicate functional interface and() method example

In the example we’ll have a range check that the passed integer is greater than 10 but less than 30. This can be done using the and() method of the Predicate interface by creating two predicates and composing them using and() so that first greater than 10 condition is evaluated and then less than 30 condition is evaluated.

public class PredicateExample {
	
  public static void main(String[] args) {
    Predicate<Integer> predicate = (i) -> i > 10;
    Predicate<Integer> andPredicate = predicate.and((i) -> i < 30);
    
    boolean val = andPredicate.test(20);
    System.out.println("val is- " + val);
    
    val = andPredicate.test(40);
    System.out.println("val is- " + val);
    
    val = andPredicate.test(5);
    System.out.println("val is- " + val);
  }
}
Output
val is- true
val is- false
val is- false

Predicate functional interface or() method example

If you have a scenario where you want to check whether the passed string starts with letter ‘A’ or ‘B’ then you can use or() method of the Predicate interface to implement that logic.

public class PredicateExample {
	
  public static void main(String[] args) {
    Predicate<String> predicate = (s) -> s.toUpperCase().startsWith("A");
    Predicate<String> orPredicate = predicate.or((s) -> s.toUpperCase().startsWith("B"));
    
    boolean val = orPredicate.test("again");
    System.out.println("val is- " + val);
    
    val = orPredicate.test("Bat");
    System.out.println("val is- " + val);
    
    val = orPredicate.test("Dog");
    System.out.println("val is- " + val);
  }
}
Output
val is- true
val is- true
val is- false

Predicate functional interface negate() method example

Suppose you already have a Predicate that checks whether the passed String starts with A or not. Now you need to check the condition if the passed String starts with any other letter but A then you can negate the existing predicate to get the predicate that can check that.

public class PredicateExample {
	
  public static void main(String[] args) {
    Predicate<String> predicate = (s) -> s.toUpperCase().startsWith("A");
    Predicate<String> predicateNegate = predicate.negate();
    
    boolean val = predicateNegate.test("again");
    System.out.println("val is- " + val);
    
    val = predicateNegate.test("Bat");
    System.out.println("val is- " + val);
    
    val = predicateNegate.test("Dog");
    System.out.println("val is- " + val);
  }
}
Output
val is- false
val is- true
val is- true

Predicate functional interface in JDK

These built-in functional interfaces are used extensively with in the JDK itself. A very good example of usage of Predicate interface is filter() method of Stream interface in Java Stream API.

filter(Predicate<? super T> predicate)- Returns a stream consisting of the elements of this stream that match the given predicate.

Example where a List was filtered to create a new List can be rewritten using the filter() method of the Stream.

public class PredicateExample {
	
  public static void main(String[] args) {
    List<Integer> myList = new ArrayList<Integer>();
    myList.add(20);
    myList.add(60);
    myList.add(40);
    myList.add(80);
    List<Integer> newList = myList.stream().filter((i) -> i > 50).collect(Collectors.toList());
    newList.forEach(System.out::println);
  }
}
Output
60
80

That's all for the topic Predicate Functional Interface Java Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment