Java Predicate

To do :

  • Negate a predicate

What is predicate in General ?

  • Predicate in general meaning is a statement about something that is either true or false.
  • In programming, predicates represent single argument functions that return a boolean value.

Predicate in java 8

  • Predicates in Java are implemented with interfaces.
  • Predicate<T> is a generic functional interface representing a single argument function that returns a boolean value. 
  • It is located in the java.util.function package.
  • It contains a test(T t) method that evaluates the predicate on the given argument.

Example :


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

class BiggerThanFive<E> implements Predicate<Integer> {

    @Override
    public boolean test(Integer v) {

        Integer five = 5;

        return v > five;
    }
}

public class JavaPredicateEx {

    public static void main(String[] args) {

        List<Integer> nums = List.of(2, 3, 1, 5, 6, 7, 8, 9, 12);

        BiggerThanFive<Integer> btf = new BiggerThanFive<>();
        nums.stream().filter(btf).forEach(System.out::println);
    }
}

Example : Lambda

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

public class JavaPredicateEx2 {

    public static void main(String[] args) {

        List<Integer> nums = List.of(2, 3, 1, 5, 6, 7, 8, 9, 12);

        Predicate<Integer> btf = n -> n > 5;

        nums.stream().filter(btf).forEach(System.out::println);
    }
}

Reference :

http://zetcode.com/java/predicate/

Leave a Comment