Java Reference
In-Depth Information
Let's take another example of the flat map operation. Suppose you have a stream of strings. How will you count
the number of the Es in the strings? The following snippet of code shows you how to do it:
long count = Stream.of("Ken", "Jeff", "Ellen")
.map(name -> name.chars())
.flatMap(intStream -> intStream.mapToObj(n -> (char)n))
.filter(ch -> ch == 'e' || ch == 'E')
.count();
System.out.println("Es count: " + count);
Es count: 4
The code maps the strings to
IntStream
. Note that the
chars()
method of the
String
class returns an
IntStream
,
not a
Stream<Character>
. The output of the
map()
method is
Stream<IntStream>
. The
flatMap()
method maps the
Stream<IntStream>
to
Stream<Stream<Character>>
and finally, flattens it to produce a
Stream<Character>
. So, the
output of the
flatMap()
method is
Stream<Character>
. The
filter()
method filters out any characters that are not
an
E
or
e
. Finally, the
count()
method returns the number of elements in the stream. The main logic is to convert the
Stream<String>
to a
Stream<Character>
. You can achieve the same using the following code as well:
long count = Stream.of("Ken", "Jeff", "Ellen")
.flatMap(name -> IntStream.range(0, name.length())
.mapToObj(name::charAt))
.filter(ch -> ch == 'e' || ch == 'E')
.count();
The
IntStream.range()
method creates an
IntStream
that contains the indexes of all characters in the input
string. The
mapToObj()
method converts the
IntStream
into a
Stream<Character>
whose elements are the characters
in the input string.
Applying the Filter Operation
The filter operation is applied on an input stream to produce another stream, which is known as the filtered stream.
The filtered stream contains all elements of the input stream for which a predicate evaluates to true. A predicate is
a function that accepts an element of the stream and returns a
boolean
value. Unlike a mapped stream, the filtered
stream is of the same type as the input stream.
The filter operation produces a subset of the input stream. If the predicate evaluates to
false
for all elements
of the input stream, the filtered stream is an empty stream. Figure
13-9
shows a pictorial view of applying a filter
operation to a stream. The figure shows that two elements (
e1
and
en
) from the input stream made it to the filtered
stream and the other two elements (
e2
and
e3
) were filtered out.