Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

Simply use Random.ints which returns an IntStream:

int[] array = new Random().ints(limit, low, high).toArray();
share|improve this answer
    
Can you please explain what is the purpose of using boxed ? –  ketazafor Sep 11 '14 at 17:18
2  
@ketazafor: You'd only want to use boxed() if you did want an object array instead of an int[]. That's your whole problem. –  Louis Wasserman Sep 11 '14 at 17:22
    
Thx for answer, one more question is there any elegant way to generate randow string using stream api ? –  ketazafor Sep 11 '14 at 17:24
1  
@ketazafor: depends on how your random String should be constructed. If it should interpret each random int as code point, combine the int stream of this answer with “Simplest way to print an IntStream as a String –  Holger Sep 11 '14 at 17:47

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

int[] array = intStream.limit(limit).toArray();
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.