Java Programming Tutorials

Java programming tutorials with many code examples!

Java random integers in range

In Java random integers in range can be produced in many ways. In this post we show how to generate random numbers using Java 8 features!

Random integers using for loop

List<Integer> forLoopRange(int limit, int from, int to) {
    Random random = new Random();
    int bound = to-from;
    List<Integer> numbers = new ArrayList<>(limit);
    for (int i = 1; i <= limit; i++) {
        numbers.add(random.nextInt(bound)+from);
    }
    return numbers;
}

When can call the above code with sample parameters – forLoopRange(limit, 20, 30):

[25, 25, 21, 26, 21, 20, 28, 28, 25, 29]

Random integers from Random.ints

The shortest and most convenient way to generate random range of integers is to use new in Java 8 method Random.ints() that returns IntStream of random ints:

List<Integer> randomInts(int limit, int from, int to) {
    Random rand = new Random();
    return rand.ints(limit, from, to).boxed().collect(toList());
}

Let’s execute it with sample parameters – randomInts(limit, 10, 20):

[17, 17, 18, 15, 19, 14, 18, 17, 19, 12]

Random numbers with IntStream.generate()

If you would like to provide your source of random numbers you can do so and generate random integers in range with IntStream.generate() like here:

List<Integer> streamRandomRange(int limit, int from, int to) {
    // use your source of entrophy here:
    Random rand = new Random();
    int bound = to - from;
    return IntStream.generate(() -> rand.nextInt(bound)+from)
            .limit(limit)
            .boxed()
            .collect(toList());
}

Sample execution of streamRandomRange(limit, 80, 90):

[82, 80, 85, 88, 89, 87, 85, 88, 82, 83]

References:

Share with the World!