Can this loop be converted to IntStream?

Is it possible to convert the next loop to use IntStream?

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

I tried just like this:

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

But it gives the following error:

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

+4
source share
2 answers

You missed the lambda expression parameter:

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

In addition, you need rangeClosedto if you want indexes to be displayed from 1 to 5 inclusive.

However, there are cleaner ways to use IntStreamto create random numbers. For instance:

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

If nis Random, you can use

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

, ,

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

Random ThreadLocalRandom :

List<Integer> nums = ThreadLocalRandom.current().ints(5, 1, 46)
                                      .boxed().collect(Collectors.toList());
+4

Source: https://habr.com/ru/post/1695968/


All Articles