Java Reference
In-Depth Information
What functional interfaces would you use for the following function descriptors (that is,
signatures of a lambda expression)? You'll find most of the answers in
table 3.2
. As a further
exercise, come up with valid lambda expressions that you can use with these functional
interfaces.
1
. T -> R
2
. (int, int) -> int
3
. T -> void
4
. () -> T
5
. (T, U) -> R
Answers:
1
. Function<T, R> is a good candidate. It's typically used for converting an object of type T into
an object of type R (for example, Function<Apple, Integer> to extract the weight of an apple).
2
. IntBinaryOperator has a single abstract method called applyAsInt representing a function
descriptor (int, int) -> int.
3
. Consumer<T> has a single abstract method called accept representing a function descriptor
T -> void.
4
. Supplier<T> has a single abstract method called get representing a function descriptor () ->
T. Alternatively, Callable<T> also has a single abstract method called call representing a
function descriptor () -> T.
5
. BiFunction<T, U, R> has a single abstract method called apply representing a function
descriptor (T, U) -> R.
To summarize the discussion about functional interfaces and lambdas,
table 3.3
provides a
summary of use cases, examples of lambdas, and functional interfaces that can be used.
Search WWH ::
Custom Search