Java Reference
In-Depth Information
map
NOTE
If you've got a function that converts a value of one type into another,
map
lets you apply
this function to a stream of values, producing another stream of the new values.
You'll probably notice fairly soon that you've been doing some kind of map operations for
years already. Say you are writing Java code that takes a list of strings and converts them to
their uppercase equivalents. You would loop over all the values in the list and call
toUpper-
case
on each element. You would then add each of the resulting values into a new
List
.
Example 3-8
is code written in this style.
Example 3-8. Converting strings to uppercase equivalents using a for loop
List
<
String
>
collected
=
new
new
ArrayList
<>();
for
for
(
String string
:
asList
(
"a"
,
"b"
,
"hello"
)) {
String uppercaseString
=
string
.
toUpperCase
();
collected
.
add
(
uppercaseString
);
}
assertEquals
(
asList
(
"A"
,
"B"
,
"HELLO"
),
collected
);
ably have guessed this, given how frequently you have implemented something similar to the
their uppercase equivalents using the stream framework.