samedi 18 mai 2019

How do I generate a list with specified size of random integers within a range in Java 8?

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




Aucun commentaire:

Enregistrer un commentaire