Predicate
layout: default
title: Predicate<T> Functional Interface
Java 8 provides a number of functional interfaces as part of the java.util.function package.
One interface is Predicate<T>, named for the mathematical concept of a function that returns a boolean value.
* It is generic, so we tell it what kind of object to test.
* Its one method takes the parameterized type as an argument, and returns a boolean.
@FunctionalInterface
public interface Predicate <T> {
public boolean test(T t);
}
Drill¶
Lambdas/com.example.lambdas.drills.UsingPredicate* Declare and define a Predicatethat tests whether an input String ends with "!!" * Declare and define a Predicate that tests whether an input String is all uppercase. * Test your two Predicates by calling their testmethods with some Strings.
Drill¶
Lambdas/com.example.lambdas.drills.PlanetUtilities
- Refactor your
filterPlanetsmethod to take aPredicate<Planet>instead of aPlanetTester.- The body of
filterPlanetswill not change becausePredicateandPlanetTesterboth have the methodboolean test(Planet).
Lambdas/com.example.lambdas.drills.FilterPlanets
- Run
FilterPlanetsagain.- Notice that your
FilterPlanetsclass is unchanged because the lambda expression is based on the function descriptor (parameter and return types) rather than on names.(Solution: PlanetUtilities2.java, FilterPlanets2.java)