Can this for loop be converted to an IntStream? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Can this for loop be converted to an IntStream? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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();
We are here to answer your question about Can this for loop be converted to an IntStream? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji