Numeric Streams Using the Random Class – Streams
Numeric Streams Using the Random Class
The following methods for building numeric unordered streams are defined in the java.util.Random class:
NumType is Int, Long, or Double, and the corresponding numtype is int, long, or double. The corresponding overloaded numtypes() methods are ints(), longs(), and doubles().
NumType
Stream
numtype
s()
NumType
Stream
numtype
s(
numtype
randomNumberOrigin,
numtype
randomNumberBound)
NumType
Stream
numtype
s(long streamSize)
NumType
Stream
numtype
s(long streamSize,
numtype
randomNumberOrigin,
numtype
randomNumberBound)
The first two methods generate an effectively unlimited sequential unordered stream of pseudorandom numtype values. For the zero-argument doubles() method, the double values are between 0.0 (inclusive) and 1.0 (exclusive). For the second method, the numtype values generated are in the half-open interval defined by the origin and the bound values.
The last two methods generate a finite sequential unordered stream of pseudorandom numtype values, where the length of the stream is limited by the specified streamSize parameter.
The examples below illustrate using a pseudorandom number generator (PRNG) to create numeric streams. The same PRNG can be used to create multiple streams. The PRNG created at (1) will be used in the examples below.
Random rng = new Random(); // (1)
The int stream created at (2) is an effectively unlimited unordered stream of int values. The size of the stream is limited to 3 by the limit() operation. However, at (3), the maximum size of the stream is specified in the argument to the ints() method. The values in both streams at (2) and (3) can be any random int values. The contents of the array constructed in the examples will, of course, vary.
IntStream iStream = rng.ints(); // (2) Unlimited, any int value
int[] intArray = iStream.limit(3).toArray(); // Limits size to 3
//[-1170441471, 1070948914, 264046613]
intArray = rng.ints(3).toArray(); // (3) Size 3, any int value
//[1011448344, -974832344, 816809715]
The unlimited unordered stream created at (4) simulates the dice throw we implemented earlier using the generate() method (p. 895). The values are between 1 and 6, inclusive. The limit() method must be used explicitly to limit the stream. The finite unordered stream created at (5) incorporates the size and the value range.
intArray = rng.ints(1, 7) // (4) Unlimited, [1, 6]
.limit(3) // Limits size to 3
.toArray(); // [5, 2, 4]
intArray = rng.ints(3, 1, 7) // (5) Size 3, [1, 6]
.toArray(); // [1, 4, 6]
The zero-argument doubles() method and the single-argument doubles(streamSize) method generate an unlimited and a limited unordered stream, respectively, whose values are between 0.0 and 1.0 (exclusive).
DoubleStream dStream = rng.doubles(3); // (6) Size 3, [0.0, 1.0)
double[] dArray = dStream.toArray();
//[0.9333794789872794, 0.7037326827186609, 0.2839257522887708]
Leave a Reply