Eos Antigen
Eos Antigen

Reputation: 388

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

Upvotes: 8

Views: 3306

Answers (2)

Holger
Holger

Reputation: 298153

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

Upvotes: 4

Eran
Eran

Reputation: 393811

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

Upvotes: 12

Related Questions