Java Program to shuffle an array using list

Java 8Object Oriented ProgrammingProgramming

Let us first create a string array and convert it to a list. After that, the shuffle would be performed.

Following is the string array −

String str[] = {"A", "B", "C", "D", "E"};

Convert the string array to list −

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

Now shuffle the array −

Collections.shuffle(list);

Example

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      String str[] = {"A", "B", "C", "D", "E"};
      List<String>list = Arrays.asList(str);
      Collections.shuffle(list);
      System.out.println("Shuffled the array using List = "+list.toString());
   }
}

Output

Shuffled the array using List = [C, B, E, D, A]
raja
Published on 26-Apr-2019 06:41:02
Advertisements