Generate an infinite stream of unbounded random long values

longs is an instance method of the Random class that is used to generate an infinite stream of random long values.

The Random class is defined in the java.util package. To import the Random class, check the following import statement.

import java.util.Random;

Syntax

public LongStream longs()

Parameters

The method has no parameters.

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();
random.longs().limit(10).forEach(System.out::println);
}
}

Explanation

  • Line 1: We import the Random class.
  • Line 7: We create an instance of the Random class.
  • Line 9: A stream of random long values are generated using the longs method. We limit the stream to 10 and print the generated random values.