Java Algorithms How to - Generate a random number from an array








Question

We would like to know how to generate a random number from an array.

Answer

import java.util.Random;

public class Main {
  public static void main(String... args) {
    int[] data = new int[] { 1, 2, 2, 2, 3, 3, 4, 5, 5, 5, 5, 5, 5 };
    System.out.print(data[new Random().nextInt(data.length)]);
  }
}

The code above generates the following result.