Java Reference
In-Depth Information
Using the Function<T,R> Interface
Six specializations of the
Function<T, R>
interface exist:
IntFunction<R>
•
LongFunction<R>
•
DoubleFunction<R>
•
ToIntFunction<T>
•
ToLongFunction<T>
•
ToDoubleFunction<T>
IntFunction<R>
,
LongFunction<R>
, and
DoubleFunction<R>
take an
int
, a
long
, and a
double
as an argument,
respectively, and return a value of type
R
.
ToIntFunction<T>
,
ToLongFunction<T>
, and
ToDoubleFunction<T>
take an
argument of type
T
and return an
int
, a
long
, and a
double
, respectively. Similar specialized functions exist for other
types of generic functions listed in the table.
•
■
the
Mapper<T>
interface in Listing 5-8 represents the same function type as
ToIntFunction<T>
in the
java.util.function
package. You created the
Mapper<T>
interface to learn how to create and use a generic functional
interface. From now on, please look at built-in functional interfaces before creating your own; use them if they meet
your needs.
Tip
The following snippet of code shows how to use the same lambda expression to represent a function that accepts
an
int
and returns its square, using four variants of the
Function<T, R>
function type:
// Takes an int and returns its square
Function<Integer, Integer> square1 = x -> x * x;
IntFunction<Integer> square2 = x -> x * x;
ToIntFunction<Integer> square3 = x -> x * x;
UnaryOperator<Integer> square4 = x -> x * x;
System.out.println(square1.apply(5));
System.out.println(square2.apply(5));
System.out.println(square3.applyAsInt(5));
System.out.println(square4.apply(5));
25
25
25
25
The
Function
interface contains the following default and static methods:
default <V> Function<T,V> andThen(Function<? super R,? extends V> after)
•
default <V> Function<V,R> compose(Function<? super V,? extends T> before)
•
static <T> Function<T,T> identity()
•