-2

I want to generate a list of random numbers between a specified range and of a certain size.

I've tried using streams, and I think this is probably the best solution. I couldn't get it working myself, but I have not learned enough about streams yet.

The following code works for my problem, but I'd like to be able to use something from the Java api if possible. If I were to use stream's map method, I would need to use a consumer with n -> ThreadLocalRandom.current().nextInt(min, max + 1), but I could not appropriately collect at the end of my stream.

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

class Scratch {
    public static void main(String[] args) {
        System.out.println(getRandList(100, 0, 10));
    }

    /**
     * Get n random integers within the range of min and max
     */
    static List<Integer> getRandList(int size, int min, int max) {
        List<Integer> integers = new ArrayList<>(size);
        for (int i = 0; i < size; i++) {
            integers.add(ThreadLocalRandom.current().nextInt(min, max + 1));
        }
        return integers;
    }
}

The referenced duplicate does not address my question directly, I wanted a List<Integer> and Oleksandr's solution provides a IntStream.

William
  • 11
  • 5

3 Answers3

0

You have the class "Random" for get random numbers.

Exemple :

Random random = new Random();
random.nextInt(bound);

After, do this with a loop.

0

Here is my first thought -

List<Integer> nums = Arrays.asList(1,2,3,4,5);

List<Integer> list = nums.stream().map(n->ThreadLocalRandom.current().nextInt(0,11)).collect(Collectors.toList());

System.out.println(list);
Geodepe
  • 147
  • 1
  • 10
-1

How about this,

List<Integer> integers = IntStream.range(0, size)
    .mapToObj(i -> ThreadLocalRandom.current().nextInt(min, max + 1))
    .collect(Collectors.toList());
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63