Shuffle elements randomly with shuffle()

The shuffle() method of Collections class shuffles the elements randomly. The same method shuffle() called multiple times gives different order of elements. The algorithm is developed by designers with some randomness basing on a seed value.

Shuffling is useful in game development. For example, using shuffle() method, the playing cards can be shuffled. This method is also useful in developing test cases by a testing engineer.

Following is the method signature

  • static void shuffle(List list1): Shuffles the existing elements of list1 randomly. For repeated execution of the method, elements with different order are obtained.

Observe, the shuffle() takes List object as parameter.

Example on Shuffle elements randomly with shuffle()
import java.util.*;
public class CollectionsShuffle
{
  public static void main(String args[])
  {
    ArrayList myList = new ArrayList();
    myList.add(50);
    myList.add(10);
    myList.add(20);
    myList.add(40);
    System.out.println("Elements before shuffle: " + myList);

    Collections.shuffle(myList);
    System.out.println("Elements after first shuffle: " + myList); 

    Collections.shuffle(myList);
    System.out.println("Elements after second shuffle: " + myList); 

    Collections.shuffle(myList);
    System.out.println("Elements after third shuffle: " + myList); 
  }
}

Shuffle elements randomly with shuffle()
Output screen on Shuffle elements randomly with shuffle()

ArrayList myList = new ArrayList();
myList.add(50); myList.add(10);
myList.add(20); myList.add(40);

An ArrayList object myList is created and added a few elements with add() method inherited from List interface.

Collections.shuffle(myList);

The myList object is passed to shuffle() method. It should be noted that the elements in the original list itself are shuffled. The method is applied three times in the program and all times a different order is obtained.

Same method shuffle() exists in class Arrays to shuffle array elements.

Leave a Comment

Your email address will not be published.