Generate random number in range

This example will generate a set of random numbers within a given range using java and java 8 techniques.

Straight up Java

The code snippet below will generate 10 random numbers by using a for loop and calling random.nextInt.

@Test
public void generate_random_number_in_range_java() {
    
    int rangeUpper = 10;
    
    Random random = new Random();
    
    List<Integer> randomNumbers = new ArrayList<>();
    
    for (int x = 0; x < rangeUpper; x++) {
        randomNumbers.add(random.nextInt(rangeUpper));          
    }

    logger.info(randomNumbers);

    assertTrue(randomNumbers.size() == 10);
}

Output

[7, 7, 7, 1, 1, 7, 4, 8, 1, 6]

Java 8

Using Java 8 Stream api we will call Random.ints while specifing a range between 1 and 10.

@Test
public void generate_random_number_in_range_java8() {

    Random random = new Random(10);

    List<Integer> randomNumbers = random.ints(0, 10).limit(10).boxed()
            .collect(Collectors.toList());

    logger.info(randomNumbers);

    assertTrue(randomNumbers.size() == 10);
}

Output

[3, 0, 3, 0, 6, 6, 7, 8, 1, 4]