Generate a finite stream of unbounded random long values
Overview
longs is an instance method of the Random class used to generate a finite stream of random long values. The number of values to be generated is passed as an argument to the method.
The Random class is defined in the java.util package. To import the Random class, use the following import statement.
import java.util.Random;
Syntax
public LongStream longs(long streamSize)
Parameters
long streamSize: This is the size of the stream
Return value
The method returns a stream of random long values.
Code
import java.util.Random;public class Main{public static void main(String[] args) {Random random = new Random();long streamSize = 10;random.longs(streamSize).forEach(System.out::println);}}
Explanation
-
Line 1: We import the
Randomclass. -
Line 7: We create an instance of the
Randomclass. -
Line 9: We define the size of the stream or the number of random values to generated.
-
Line 11: A stream of random
longvalues are generated using thelongsmethod passing the stream size as an argument. Next, the generated random values are printed to the console.