Java Reference
In-Depth Information
Face Frequency
1 999339
2 999937
3 1000302
4 999323
5 1000183
6 1000916
Fig. 17.19
|
Rolling a die 6,000,000 times with streams. (Part 2 of 2.)
Creating an
IntStream
of Random Values
In Java SE 8, class
SecureRandom
has overloaded methods
ints
,
longs
and
doubles
, which
it inherits from class
Random
(package
java.util
). These methods return
IntStream
,
Long-
Stream
and
DoubleStream
, respectively, that represent streams of random numbers. Each
method has four overloads. We describe the
ints
overloads here—methods
longs
and
dou-
bles
perform the same tasks for streams of
long
and
double
values, respectively:
•
ints()
—creates an
IntStream
for an
infinite stream
of random
int
s. An
infinite
stream
has an
unknown
number of elements—you use a short-circuiting terminal
operation to complete processing on an infinite stream. We'll use an infinite
stream in Chapter 23 to find prime numbers with the Sieve of Eratosthenes.
•
ints(long)
—creates an
IntStream
with the specified number of random
int
s.
•
ints(int,
int)
—creates an
IntStream
for an
infinite stream
of random
int
val-
ues in the range starting with the first argument and up to, but not including, the
second argument.
•
ints(long,
int,
int)
—creates an
IntStream
with the specified number of ran-
dom
int
values in the range starting with the first argument and up to, but not
including, the second argument.
Line 17 uses the last overloaded version of
ints
to create an
IntStream
of 6,000,000 ran-
dom integer values in the range 1-6.
Converting an
IntStream
to a
Stream<Integer>
We summarize the roll frequencies in this example by collecting them into a
Map<Integer,
Long>
in which each
Integer
key is a side of the die and each
Long
value is the frequency of
that side. Unfortunately, Java does not allow primitive values in collections, so to summarize
the results in a
Map
, we must first convert the
IntStream
to a
Stream<Integer>
. We do this
by calling
IntStream
method
boxed
.
Summarizing the Die Frequencies
Lines 19-20 call
Stream
method
collect
to summarize the results into a
Map<Integer,
Long>
. The first argument to
Collectors
method
groupingBy
(line 19) calls
static
method
identity
from interface
Function
, which creates a
Function
that simply returns
its argument. This allows the actual random values to be used as the
Map
's keys. The second
argument to method
groupingBy
counts the number of occurrences of each key.
Displaying the Results
Lines 21-22 call the resulting
Map
's
forEach
method to display the summary of the results.
This method receives an object that implements the
BiConsumer
functional interface as an