Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this for loop be converted to an IntStream?

Tags:

java

java-8

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

for (int i =1; i<=5; i++)
{
   nums.add(n.nextInt(45)+1);
}

I tried as following very simply:

IntStream.range(1,5).forEach(nums.add(n.nextInt(45)+1));

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));

like image 206
Eos Antigen Avatar asked Apr 09 '18 09:04

Eos Antigen


Video Answer


2 Answers

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();
like image 186
Eran Avatar answered Nov 09 '22 16:11

Eran


If n is a Random, you can use

n.ints(5, 1, 46).forEach(nums::add);

but if you are actually creating the list rather than adding to an existing list, you can use

List<Integer> nums = n.ints(5, 1, 46).boxed().collect(Collectors.toList());

More than often, you don’t need a dedicated Random instance and ThreadLocalRandom is sufficient and more efficient:

List<Integer> nums = ThreadLocalRandom.current().ints(5, 1, 46)
                                      .boxed().collect(Collectors.toList());
like image 43
Holger Avatar answered Nov 09 '22 17:11

Holger