简体   繁体   中英

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

I am trying to generate random array of integers using new Stream API in Java 8. But I haven't understood this API clearly yet. So I need help. Here is my code.

Random random = new Random();
IntStream intStream = random.ints(low, high);
int[] array =  intStream.limit(limit) // Limit amount of elements
                                    .boxed() // cast to Integer
                                    .toArray();

But this code returns array of objects. What is wrong with it?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM