Java Utility Library

Java Random - ints() Method



The java.util.Random.ints() method returns a stream producing the given streamSize number of pseudorandom int values, each conforming to the given origin (inclusive) and bound (exclusive).

Syntax

public IntStream ints(long streamSize,
                      int randomNumberOrigin,
                      int randomNumberBound)

Parameters

streamSize Specify the number of values to generate.
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 int values, each with the given origin (inclusive) and bound (exclusive).

Exception

  • Throws IllegalArgumentException, if streamSize is less than zero.
  • Throws IllegalArgumentException, if randomNumberOrigin is greater than or equal to randomNumberBound.

Example:

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

import java.util.*;
import java.util.stream.IntStream;

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

    //generating a stream containing 10 int random
    //numbers between 500(inclusive) and 1000(exclusive)
    IntStream stream = rand.ints(10, 500, 1000);

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

One of the possible outcome is given below:

700
563
785
564
880
840
709
962
725
505

❮ Java.util - Random