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));
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();
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With