Java Utility Library

Java Random - longs() Method



The java.util.Random.longs() method returns an effectively unlimited stream of pseudorandom long values, each conforming to the given origin (inclusive) and bound (exclusive).

Syntax

public LongStream longs(long randomNumberOrigin,
                        long randomNumberBound)

Parameters

randomNumberOrigin Specify the origin (inclusive) of each random value.
randomNumberBound Specify the bound (exclusive) of each random value.

Return Value

Returns a stream of pseudorandom long values, each with the given origin (inclusive) and bound (exclusive).

Exception

Throws IllegalArgumentException, if randomNumberOrigin is greater than or equal to randomNumberBound.

Example:

In the example below, the java.util.Random.longs() method is used to get a stream of pseudorandom long values in the given range.

import java.util.*;
import java.util.stream.LongStream;

public class MyClass {
  public static void main(String[] args) {
    //creating a random object
    Random rand = new Random();

    //generating a stream containing long random
    //numbers between 500(inclusive) and 1000(exclusive)
    LongStream stream = rand.longs(500, 1000);

    //printing 10 random numbers from the stream
    stream.limit(10).forEach(System.out::println); 
  }
}

One of the possible outcome is given below:

618
895
896
779
631
942
543
934
640
537

❮ Java.util - Random