java.util.function.Predicate example

A predicate is often used in mathematics that something that takes a value for an argument and then returns true or false. In the examples below we will show common uses of java.util.function.Predicate.

Setup

Predicate<String> hasLengthOf10 = new Predicate<String>() {
    @Override
    public boolean test(String t) {
        return t.length() > 10;
    }
};

Predicate test

The 'test' method evalues the predicate on the given argument. In this example, we test the string to verify it has a length of 10.

@Test
public void predicate_test() {

    String randomString = "The 2014 Winter Olympics, officially "
            + "known as the XXII Olympic Winter Games, "
            + "is a major international multi-sport "
            + "event currently being held in Sochi, "
            + "Russia, in the tradition of the " + "Winter Olympic Games";

    boolean outcome = hasLengthOf10.test(randomString);

    assertTrue(outcome);
}

Predicate and

The predicate 'and' method returns a composed predicate that represents a short-circuiting logical AND of this predicate and another. Ihe code below we will validate that the string is not null and it has length of greater than 10.

@Test
public void predicate_and() {

    Predicate<String> nonNullPredicate = Objects::nonNull;

    String nullString = null;

    boolean outcome = nonNullPredicate.and(hasLengthOf10).test(nullString);
    assertFalse(outcome);

    String lengthGTThan10 = "Welcome to the machine";

    boolean outcome2 = nonNullPredicate.and(hasLengthOf10).test(
            lengthGTThan10);

    assertTrue(outcome2);
}

Predicate negate

The predicate 'negate' method returns a predicate that represents the logical negation or opposite. In the case below, the string has a length of 10 but since we call the negate it will return false.

@Test
public void predicate_negate() {

    String lengthGTThan10 = "Thunderstruck is a 2012 children's "
            + "film starring Kevin Durant";

    boolean outcome = hasLengthOf10.negate().test(lengthGTThan10);
    assertFalse(outcome);
}

Predicate or

The predicate 'or' method returns a composed predicate that represents a short-circuiting logical OR of this predicate and another. We create an additional predicate that checks to see if the string contains the letter "A" and then also check if string has the length of 10.

@Test
public void predicate_or() {

    Predicate<String> containsLetterA = p -> p.contains("A");

    String containsA = "And";

    boolean outcome = hasLengthOf10.or(containsLetterA).test(containsA);

    assertTrue(outcome);
}