Generate stream of random numbers
Its not possible for any computer to generate real random numbers, but they can generate pseudorandom numbers. Pseudorandom numbers are generated based on an algorithm and they are nearly like random numbers. Java’s Random class uses to generate pseudorandom numbers and this formula needs initial value or called seed.
Random class have two constructors:
Random(): No need to provide seed so if you create multiple Random objects, then all of them will likely generate different pseudorandom number sequence.
Random(long seed): Takes seed as initial value. This will be useful if you want to regenerate same sequence again.
I will use JShell for demo because we are just working on Random class so it will be easier. so lets start JShell and create Random object.
ints() method in the Random class will return unlimited stream of pseudorandom numbers. We can limit this stream by calling limit method on the stream like below:
I used terminal operation ‘forEach’ at the end to show the output. We can make this code shorter by using ints(long streamSize) method in the Random class. This will generate limited IntStream;
We can generate numbers with in a range by calling ‘ints(long streamSize, int randomNumberOrigin, int randomNumberBound)’ method in Random;
All of the above methods are available in long and double versions also, so those methods return LongStream and DoubleStream. Instead of printing it to console we can collect them into a list easily using Collectors, like below;