Java Reference
In-Depth Information
type, it is suffixed with
To
and the primitive type, as in
mapToLong
.
Figure 4-2. LongFunction
There are also specialized versions of
Stream
for these primitive types that prefix the type
name, such as
LongStream
. In fact, methods like
mapToLong
don't return a
Stream
; they re-
turn these specialized streams. On the specialized streams, the
map
implementation is also
maps a
long
to a
long
. It's also possible to get back from a primitive stream to a boxed
stream through higher-order function variations such as
mapToObj
and the
boxed
method,
which returns a stream of boxed objects such as
Stream<Long>
.
Figure 4-3. LongUnaryOperator
It's a good idea to use the primitive specialized functions wherever possible because of the
performance benefits. You also get additional functionality available on the specialized
streams. This allows you to avoid having to implement common functionality and to use
code that better conveys the intent of numerical operations. You can see an example of how
to use this functionality in
Example 4-4
.
Example 4-4. Using summaryStatistics to understand track length data
public
public static
void
printTrackLengthStatistics
(
Album album
) {
IntSummaryStatistics trackLengthStats
=
album
.
getTracks
()
.
mapToInt
(
track
->
track
.
getLength
())
.
summaryStatistics
();
static
void