Selected Interfaces in the Java SE Platform API
A functional interface, like any other interface, can always be implemented by a class. The @FunctionalInterface annotation on a functional interface in the Java SE Platform API documentation indicates that the implementation of the functional interface is meant to be implemented by lambda expressions.
In the Java SE Platform API, not all interfaces with one abstract method declaration are marked with the @FunctionalInterface annotation. Such single-abstract-method (SAM) interfaces usually elicit specific behavior in objects which is best provided by the class of an object, and not by users of the class. Examples of single-abstract-method interfaces that should be implemented by classes include the following interfaces from the java.lang package:
- Comparable<T> for creating an object that can be compared with another object according to their natural ordering (§14.4, p. 761)
- Iterable<T> for creating an object that represents a collection in a for(:) loop to iterate over its elements (§15.2, p. 791)
- AutoCloseable for creating an object that represents a resource that is automatically closed when exiting a try-with-resources statement (§7.7, p. 412)
- Readable for creating an object that is a source for reading characters (§20.3, p. 1249)
The Java SE Platform API also has ample examples of functional interfaces that are intended to be implemented by lambda expressions. Built-in general-purpose functional interfaces provided in the java.util.function package are discussed in §13.4, p. 695. In addition, the following specialized functional interfaces are worth noting:
- java.util.Comparator<T> with the method compare() for defining criteria for comparing two objects according to their total ordering (§14.5, p. 769)
- java.lang.Runnable with the method run() for defining code to be executed in threads (§22.3, p. 1370)
- java.util.concurrent.Callable<V> with the method call() for defining code to be executed in threads, that can return a result and throw an exception (§23.2, p. 1423)