How to Shuffle or Randomize a List in Java

In this post, we will discuss how to shuffle or randomize a List in Java using Fisher–Yates shuffle algorithm and shuffle() method provided by the Collections class.


Randomize a List using Fisher–Yates Shuffle Algorithm:

Fisher–Yates shuffle algorithm can be used for generating random permutations of a finite sequence where every permutation is equally likely. Since it is an in-place algorithm and takes linear time, it is recommended approach for shuffling an array or list in any programming language.

Below is an implementation of Fisher–Yates shuffle algorithm which shuffles the list from highest index to lowest:


Download   Run Code


Below is an equivalent version of above algorithm which shuffles the list from lowest index to highest:


Download   Run Code


Randomize a list using Collections.shuffle()

The simplest way to randomize a list is to use Collections.shuffle() method as shown below:


It is worth noting that internally Collections.shuffle() also uses Fisher–Yates shuffle algorithm by creating an intermediary array from the list, shuffling the array and converting the array back into the list. Below implementation in Java is pretty much similar to JDK implementation:


Download   Run Code

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of