Java Collection How to - Randomly Generate From A Given Array without using shuffle method








Question

We would like to know how to randomly Generate From A Given Array without using shuffle method.

Answer

import java.util.Arrays;
import java.util.List;
import java.util.Random;
/*from w ww  . j  ava 2 s  . co  m*/
public class Main {
  public static void main(String[] args) {
    String[] peoples = { "A", "B", "C", "D", "E", "F" };
    List<String> names = Arrays.asList(peoples);

    for (int i = 0; i < peoples.length; i++) {
      int index = new Random().nextInt(names.size());
      String anynames = names.get(index);
      System.out.println(anynames);

    }

  }
}

The code above generates the following result.