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.
JavaScript
x
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
:
JavaScript
int[] array = new Random().ints(size, lowBound, highBound).toArray();