Java Collection How to - Shuffle elements of an array








Question

We would like to know how to shuffle elements of an array.

Answer

    // ww w  .ja v a2s. com

 
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    String[] alphabets = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J" };

    List<String> list = Arrays.asList(alphabets);

    Collections.shuffle(list);

    for (String alpha : list) {
      System.out.print(alpha + " ");
    }
  }
}

The code above generates the following result.