Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Collections.shuffle() Method in Java with Examples

  • Difficulty Level : Easy
  • Last Updated : 27 Oct, 2021

shuffle() method of Collections class as the class name suggests is present in utility package known as java.util that shuffles the elements in the list.

There are two ways with which we can use to implement in our programs that are as follows:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

  1. Using the pre-defined source of randomness
  2. Using the user-provided source of randomness

Way 1: Shuffling a given list using the pre-defined source of randomness.

Syntax:



public static void shuffle(List mylist)

Exception Thrown: UnsupportedOperationException is thrown if the given list or its list-iterator does not support the set operation.

Example:

Java




// Java program to demonstrate
// working of shuffle() method
// of Collections class
 
// Importing utility classes
import java.util.*;
 
// Main class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an empty ArrayList of string type
        ArrayList<String> mylist = new ArrayList<String>();
 
        // Adding custom input elements to list object
        mylist.add("code");
        mylist.add("quiz");
        mylist.add("geeksforgeeks");
        mylist.add("quiz");
        mylist.add("practice");
        mylist.add("qa");
 
        // Printing list before shuffling
        System.out.println("Original List : \n" + mylist);
 
        // Shuffling the list
        Collections.shuffle(mylist);
 
        // Printing list after shuffling
        System.out.println("\nShuffled List : \n" + mylist);
    }
}

 
 

Output
Original List : 


Shuffled List : 

 

Way 2:  Shuffling a given list using the user-provided source of randomness. 

Here an additional parameter that is provided which above specified “rndm” is the source of randomness to shuffle the list.
 

Syntax:



public static void shuffle(List mylist, Random rndm)

Parameters: Here it takes two parameters as listed 

  • List
  • Source of randomness  

Exceptions:  UnsupportedOperationException if the specified list or its list-iterator does not support the set operation.

Example:

Java




// Java Program to demonstrate working of shuffle()
// with user provided source of randomness
 
// Importing required utility classes
import java.util.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty ArrayList of string type
        ArrayList<String> mylist = new ArrayList<String>();
 
        // Adding custom input elements to above created
        // object
        mylist.add("code");
        mylist.add("quiz");
        mylist.add("geeksforgeeks");
        mylist.add("quiz");
        mylist.add("practice");
        mylist.add("qa");
 
        // Print and display the elements of List on console
        System.out.println("Original List : \n" + mylist);
 
        // Shuffling the given list
        // using Random() method
        Collections.shuffle(mylist, new Random());
 
        // Print the updated list on console
        System.out.println(
            "\nShuffled List with Random() : \n" + mylist);
 
        // Shuffling list by using Random(3)
        Collections.shuffle(mylist, new Random(3));
 
        // Print the updated list on console
        System.out.println(
            "\nShuffled List with Random(3) : \n" + mylist);
 
        // Again shuffling list by using Random(3)
        Collections.shuffle(mylist, new Random(5));
 
        System.out.println(
            "\nShuffled List with Random(5) : \n" + mylist);
    }
}
Output
Original List : 


Shuffled List with Random() : 
[quiz, practice, quiz, geeksforgeeks, qa, code]

Shuffled List with Random(3) : 


Shuffled List with Random(5) : 
[geeksforgeeks, qa, quiz, code, practice, quiz]

 

But do remember certain important points as listed below prior to implementing this method as listed below as follows:

  • Internal working: This method randomly permutes elements randomly in a list.
  • Runtime: It runs in a linear time.
  • Access to elements:
    • It traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element to its “current position”.
    • Thereafter elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive.

Note: If the provided list does not implement the RandomAccess interface, like LinkedList, and is large, it first copies the list into an array, then shuffles the array copy, and finally copies the array back into the list. This makes sure that the time remains linear.

 

This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!