Can this for loop be converted to an IntStream?

Is there any way the following for loop could be converted to use an IntStream?

for (int i =1; i<=5; i++)

I tried as following very simply:


But it outputs the following error:

incompatible types: boolean cannot be converted to IntConsumer IntStream.range(1,5).forEach(nums.add(n.nextInt(45)+1));


You were missing the parameter of the lambda expression:

IntStream.rangeClosed(1,5).forEach(i -> nums.add(n.nextInt(45)+1));

Besides, you need rangeClosed if you want the indices to go from 1 to 5 inclusive.

That said, there are cleaner ways to use IntStream to produce random numbers. For example:

Random rand = new Random();
int[] nums = rand.ints(5,1,46).toArray();

Leave a Reply

Your email address will not be published. Required fields are marked *