Java Reference
In-Depth Information
So far, we've showed how you can make use of functional interfaces to pass lambdas. But you
had to define your own interfaces. In the next section we explore new interfaces that were added
to Java 8 that you can reuse to pass multiple different lambdas.
3.4. Using functional interfaces
As you learned in section 3.2.1 , a functional interface specifies exactly one abstract method.
Functional interfaces are useful because the signature of the abstract method can describe the
signature of a lambda expression. The signature of the abstract method of a functional interface
is called a function descriptor . So in order to use different lambda expressions, you need a set of
functional interfaces that can describe common function descriptors. There are several
functional interfaces already available in the Java API such as Comparable, Runnable, and
Callable, which you saw in section 3.2 .
The Java library designers for Java 8 have helped you by introducing several new functional
interfaces inside the java.util.function package. We describe the interfaces Predicate, Consumer,
and Function next, and a more complete list is available in table 3.2 at the end of this section.
3.4.1. Predicate
The java.util.function.Predicate<T> interface defines an abstract method named test that
accepts an object of generic type T and returns a boolean. It's exactly the same one that you
created earlier, but is available out of the box! You might want to use this interface when you
need to represent a boolean expression that uses an object of type T. For example, you can
define a lambda that accepts String objects, as shown in the following listing.
Listing 3.2. Working with a Predicate
@FunctionalInterface
public interface Predicate<T>{
boolean test(T t);
}
public static <T> List<T> filter(List<T> list, Predicate<T> p) {
List<T> results = new ArrayList<>();
for(T s: list){
if(p.test(s)){
results.add(s);
 
Search WWH ::




Custom Search