Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
java

Generate a finite stream of bounded random long values

abhilash

Overview

In Java, longs is an instance method of the Random class that is used to generate a stream of pseudorandom long values of a specified size. Each of the generated values adhere to the supplied origin (inclusive) and bound (exclusive).

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

import java.util.Random;

Syntax

public LongStream longs(long streamSize, long randomNumberOrigin, long randomNumberBound)

Parameters

  • long streamSize: This is the size of the stream.
  • long randomNumberOrigin: This is the origin of each value that is generated.
  • long randomNumberBound: This is the bound of each value that is generated.

Return value

The method returns a stream of random long values.

Code example

import java.util.Random;
import java.util.stream.LongStream;

public class Main{

    public static void main(String[] args) {

        Random random = new Random();

        long streamSize = 8;

        long randomNumberOrigin = 1;

        long randomNumberBound = 7;

        LongStream ds = random.longs(streamSize, randomNumberOrigin, randomNumberBound);

        ds.forEach(System.out::println);

    }
}
Implementation of the "longs" method

Code explanation

  • Lines 1–2: We import the relevant classes.
  • Line 8: We create an instance of the Random class.
  • Line 10: We define the number of random values that need to be generated.
  • Line 12: We define the origin for each random number.
  • Line 14: We define the bound for each random number.
  • Line 16: We get a LongStream of random numbers. The stream size, origin, and bound are passed as arguments to the longs() method.
  • Line 18: We print the generated random values to the console.

RELATED TAGS

communitycreator
java
RELATED COURSES

View all Courses

Keep Exploring