Shuffle or Randomize a list in Java

JavaServer Side ProgrammingProgramming

To shuffle a list in Java, the code is as follows −

Example

 Live Demo

import java.util.*;
public class Demo{
   public static void main(String[] args){
      ArrayList<String> my_list = new ArrayList<String>();
      my_list.add("Hello");
      my_list.add(",");
      my_list.add("this");
      my_list.add("is");
      my_list.add("a");
      my_list.add("sample");
      System.out.println("The original list is : \n" + my_list);
      Collections.shuffle(my_list);
      System.out.println("\n The shuffled list is : \n" + my_list);
   }
}

Output

The original list is :
[Hello, ,, this, is, a, sample]
The shuffled list is :
[a, is, ,, Hello, this, sample]

A class named Demo contains the main function. Here, an array list is defined and elements are added to the array list with the help of the ‘add’ function. The original list is printed, and then the ‘shuffle’ function is called on this array list. This way, the elements in the list will be shuffled and then printed on the screen.

raja
Published on 17-Aug-2020 08:51:58
Advertisements