Skip to content
Advertisement

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?

Advertisement

Answer

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();
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement