Java Reference
In-Depth Information
I'm sure you've written some code that looks like this: it's called the
filter
pattern. The
central idea of
filter
is to retain some elements of the
Stream
, while throwing others out.
Example 3-11
shows how you would write the same code in a functional style.
Example 3-11. Functional style
List
<
String
>
beginningWithNumbers
=
Stream
.
of
(
"a"
,
"1abc"
,
"abc1"
)
.
filter
(
value
->
isDigit
(
value
.
charAt
(
0
)))
.
collect
(
toList
());
assertEquals
(
asList
(
"1abc"
),
beginningWithNumbers
);
Much like
map
,
filter
is a method that takes just a single function as an argument—here
we're using a lambda expression. This function does the same job that the expression in the
if
statement did earlier. Here, it returns
true
if the
String
starts with a digit. If you're re-
factoring legacy code, the presence of an
if
statement in the middle of a
for
loop is a pretty
strong indicator that you really want to use
filter
.
Because this function is doing the same job as the
if
statement, it must return either
true
or
false
for a given value. The
Stream
after the filter has the elements of the
Stream
before-
hand, which evaluated to
true
. The functional interface for this type of function is our old
Figure 3-6. The Predicate interface
flatMap
NOTE
streams together.