How to shuffle an array in Java?

Java 8Object Oriented ProgrammingProgramming

Declare a string array and add elements in the form of letters −

String[] letters = { "P", "Q", "R", "S", "T", "U","V", "W", "X", "Y", "Z" };

Convert the above array to list −

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

Now, create a shuffled array using the Random class object and generate the random letters with nextInt() −

int len = list.size();
System.out.println("Shuffled array...");
for (int i = 0; i < letters.length; i++) {
   int index = new Random().nextInt(len);
   String shuffle = list.get(index);
   System.out.println(shuffle);
}

Example

 Live Demo

import java.util.Arrays;
import java.util.List;
import java.util.Random;
public class Demo {
   public static void main(String[] args) {
      String[] letters = { "P", "Q", "R", "S", "T", "U","V", "W", "X", "Y", "Z" };
      System.out.println("Initial array = "+Arrays.toString(letters));
      List<String>list = Arrays.asList(letters);
      int len = list.size();
      System.out.println("Shuffled array...");
      for (int i = 0; i < letters.length; i++) {
         int index = new Random().nextInt(len);
         String shuffle = list.get(index);
         System.out.println(shuffle);
      }
   }
}

Output

Initial array = [P, Q, R, S, T, U, V, W, X, Y, Z]
Shuffled array...
P
X
S
X
W
S
V
R
Y
Q
R
raja
Published on 23-Apr-2019 12:59:13
Advertisements