Generate an infinite stream of bounded random long values

Overview

longs is an instance method of the Random class used to generate an infinite stream of pseudorandom long values, each adhering to the supplied origin (inclusive) and bound (exclusive).

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 randomNumberOrigin, long randomNumberBound)

Parameters

  • long randomNumberOrigin: This is the origin of each value generated.
  • long randomNumberBound: This is the bound of each value generated.

Return value

The method returns a stream of random long values.

Code

import java.util.Random;
import java.util.stream.LongStream;
public class Main{
public static void main(String[] args) {
Random random = new Random();
long randomNumberOrigin = 1;
long randomNumberBound = 7;
LongStream ds = random.longs(randomNumberOrigin, randomNumberBound);
ds.limit(10).forEach(System.out::println);
}
}

Explanation

  • Lines 1-2: We import the relevant classes.
  • Line 8: We create an instance of the Random class.
  • Line 10: We define the lower bound for each random number.
  • Line 12: We define the upper bound for each random number.
  • Line 14: We get a LongStream of random numbers. The lower and upper bounds are passed as parameters to the longs() method.
  • Line 16: We limit the stream of values to 10 and print the generated random values.

Free Resources