Java Reference
In-Depth Information
Figure
13-7
depicts the application of the map operation on a stream. It shows element e1 from the input stream
being mapped to element et1 in the mapped stream, element e2 mapped to et2, etc.
map(e)
e1
et1
e2
et2
e3
et3
en
etn
Output stream
Input stream
Figure 13-7.
A pictorial view of the map operation
Mapping a stream to another stream is not limited to any specific type of elements. You can map a stream of
T
to
a stream of type
S
, where
T
and
S
may be the same or different types. For example, you can map a stream of
Person
to a stream of
int
where each
Person
element in the input stream maps to the
Person
's id in the mapped stream.
You can apply the map operation on a stream using one of the following methods of the
Stream<T>
interface:
<R> Stream<R> map(Function<? super T,? extends R> mapper)
•
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
•
IntStream mapToInt(ToIntFunction<? super T> mapper)
•
LongStream mapToLong(ToLongFunction<? super T> mapper)
•
The map operation takes a function as an argument. Each element from the input stream is passed to the
function. The returned value from the function is the mapped element in the mapped stream. Use the
map()
method
to perform the mapping to reference type elements. If the mapped stream is of a primitive type, use other methods;
for example, use the
mapToInt()
method to map a stream of a reference type to a stream of
int
. The
IntStream
,
LongStream
, and
DoubleStream
interfaces contain similar methods to facilitate mapping of one type of stream to
another. The methods supporting the map operation on an
IntStream
are as follows:
IntStream map(IntUnaryOperator mapper)
•
DoubleStream mapToDouble(IntToDoubleFunction mapper)
•
LongStream mapToLong(IntToLongFunction mapper)
•
<U> Stream<U> mapToObj(IntFunction<? extends U> mapper)
The following snippet of code creates an
IntStream
whose elements are integers from 1 to 5, maps the elements
of the stream to their squares, and prints the mapped stream on the standard output. Note that the
map()
method
used in the code is the
map()
method of the
IntStream
interface.
•
IntStream.rangeClosed(1, 5)
.map(n -> n * n)
.forEach(System.out::println);