Java Reference
In-Depth Information
this interface when you need to define a lambda that maps information from an input object to
an output (for example, extracting the weight of an apple or mapping a string to its length). In
the listing that follows we show how you can use it to create a method map to transform a list of
Strings into a list of Integers containing the length of each String.
Listing 3.4. Working with a
Function
Primitive specializations
We described three functional interfaces that are generic: Predicate<T>, Consumer<T>, and
Function<T, R>. There are also functional interfaces that are specialized with certain types.
To refresh a little: every Java type is either a reference type (for example, Byte, Integer, Object,
List) or a primitive type (for example, int, double, byte, char). But generic parameters (for
example, the T in Consumer<T>) can be bound only to reference types. This is due to how
primitive type into a corresponding reference type. This mechanism is called
boxing
. The
opposite approach (that is, converting a reference type into a corresponding primitive type) is
called
unboxing
. Java also has an
autoboxing
mechanism to facilitate the task for programmers:
boxing and unboxing operations are done automatically. For example, this is why the following
code is valid (an int gets boxed to an Integer):
2
Some other languages such as C# don't have this restriction. Other languages such as Scala
have only reference types. We revisit this issue in
chapter 16
.
Search WWH ::
Custom Search