Java Reference
In-Depth Information
•
Finally, to display the summary of the words and their counts by letter (i.e., the
concordance), lines 32-37 pass a lambda to
Map
method
forEach
. The lambda (a
BiConsumer
) receives two parameters—
letter
and
wordList
represent the
Character
key and the
List
value, respectively, for each key-value pair in the
Map
produced by the preceding
collect
operation. The body of this lambda has two
statements, so it
must
be enclosed in curly braces. The statement in line 34 dis-
plays the
Character
key on its own line. The statement in lines 35-36 gets a
Stream<Map.Entry<String,
Long>>
from the
wordList
, then calls
Stream
meth-
od
forEach
to display the key and value from each
Map.Entry
object.
In Fig. 6.7, we demonstrated rolling a six-sided die 6,000,000 times and summarizing the
frequencies of each face using
external iteration
(a
for
loop) and a
switch
statement that
determined which counter to increment. We then displayed the results using separate
statements that performed external iteration. In Fig. 7.7, we reimplemented Fig. 6.7, re-
placing the entire
switch
statement with a single statement that incremented counters in
an array—that version of rolling the die still used external iteration to produce and sum-
marize 6,000,000 random rolls and to display the final results. Both prior versions of this
example, used mutable variables to control the external iteration and to summarize the re-
sults. Figure 17.19 reimplements those programs with a
single statement
that does it all, us-
ing lambdas, streams, internal iteration and no mutable variables to roll the die 6,000,000
times, calculate the frequencies and display the results.
1
// Fig. 17.19: RandomIntStream.java
2
// Rolling a die 6,000,000 times with streams
3
import
java.security.SecureRandom;
4
import
java.util.Map;
5
import
java.util.function.Function;
6
import
java.util.stream.IntStream;
7
import
java.util.stream.Collectors;
8
9
public class
RandomIntStream
10
{
11
public static void
main(String[] args)
12
{
13
SecureRandom random =
new
SecureRandom();
14
15
// roll a die 6,000,000 times and summarize the results
16
System.out.printf(
"%-6s%s%n"
,
"Face"
,
"Frequency"
);
17
random.ints(
6_000_000
,
1
,
7
)
18
.boxed()
19
.collect(Collectors.groupingBy(
Function.identity()
,
20
Collectors.counting()))
21
.forEach((face, frequency) ->
22
System.out.printf(
"%-6d%d%n"
, face, frequency));
23
}
24
}
// end class RandomIntStream
Fig. 17.19
|
Rolling a die 6,000,000 times with streams. (Part 1 of 2.)