Java Reference
In-Depth Information
Using Functional Interfaces
Functional interfaces are used in two contexts by two different types of users:
By the library designers for designing APIs
By library users for using the APIs
Functional interfaces are used to design APIs by library designers. They are used to declare a parameter's type
and return type in method declarations. They are used the same way non-functional interfaces are used. Functional
interfaces existed in Java since the beginning, and Java 8 has not changed the way they are used in designing the APIs.
In Java 8, library users use functional interfaces as target types for lambda expressions. That is, when a method
in the API takes a functional interface as an argument, the user of the API should use a lambda expression to pass the
argument. Using lambda expressions has the benefit of making the code concise and more readable.
In this section, I will show you how to design APIs using functional interfaces and how to use lambda expressions
to use the APIs. Functional interfaces have been used heavily in designing the Java library for Collection and Stream
APIs that I will cover in Chapter 13 and 14.
I will use one enum and two classes in subsequent examples. The Gender enum, shown in Listing 5-11, contains
two constants to represent the gender of a person. The Person class, shown in Listing 5-12, represents a person; it
contains, apart from other methods, a getPersons() method that returns a list of persons.
Listing 5-11. A Gender enum
// Gender.java
package com.jdojo.lambda;
public enum Gender {
MALE, FEMALE
}
Listing 5-12. A Person Class
// Person.java
package com.jdojo.lambda;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import static com.jdojo.lambda.Gender.MALE;
import static com.jdojo.lambda.Gender.FEMALE;
public class Person {
private String firstName;
private String lastName;
private LocalDate dob;
private Gender gender;
public Person(String firstName, String lastName, LocalDate dob, Gender gender) {
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
this.gender = gender;
}
 
Search WWH ::




Custom Search