Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random array of ints using Stream API Java 8?

People also ask

How do you generate a random array of integers in Java?

In order to generate random array of integers in Java, we use the nextInt() method of the java. util. Random class. This returns the next random integer value from this random number generator sequence.

What are the Stream API methods in Java 8?

With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.

How do you generate a random array index in Java?

Math. random() generates a random number between 0 and 1. If you multiply that number by the length of your array, you will get an random index for the array.

Is Stream API introduced in Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.


If you want primitive int values, do not call IntStream::boxed as that produces Integer objects by boxing.

Simply use Random::ints which returns an IntStream:

int[] array = new Random().ints(size, lowBound, highBound).toArray();

There's no reason to boxed(). Just receive the Stream as an int[].

int[] array = intStream.limit(limit).toArray();

To generate random numbers from range 0 to 350, limiting the result to 10, and collect as a List. Later it could be typecasted.

However, There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned.

List<Object> numbers =  new Random().ints(0,350).limit(10).boxed().collect(Collectors.toList());

and to get thearray of int use

int[] numbers =  new Random().ints(0,350).limit(10).toArray();

tl;dr

ThreadLocalRandom     // A random number generator isolated to the current thread.
.current()            // Returns the current thread's `ThreadLocalRandom` object.
.ints( low , high )   // Pass the "origin" (inclusive) and "bound" (exclusive).
.limit( 100 )         // How many elements (integers) do you want in your stream?
.toArray()            // Convert the stream of `int` values into an array `int[]`. 

ThreadLocalRandom

You can do it using ThreadLocalRandom.

The ints method generates an IntStream within your specified bounds. Note the the low is inclusive while the high is exclusive. If you want to include your high number, just add one while calling the ints method.

int[] randInts = ThreadLocalRandom.current().ints( low , high ).limit(100).toArray();

See this code run live at IdeOne.com.