This post will discuss how to shuffle an ArrayList in Java using Fisher–Yates shuffle algorithm and shuffle() method provided by the Collections class.

1. Using Fisher–Yates Shuffle Algorithm

The Fisher-Yates shuffle is a classic algorithm for generating random permutations of a finite sequence. It works by iterating over the elements of the list from the last to the first and swapping each element with a randomly chosen element from the remaining ones. It is an in-place algorithm that takes linear time and does not require any extra space. Following is a Java implementation of the Fisher–Yates shuffle algorithm, which shuffles a list from the last index to the first using a loop and the Collections.swap() method:

Download  Run Code

 
Following is an equivalent version of the above algorithm, which shuffles a list starting from the first index to the last index:

Download  Run Code

2. Using Collections.shuffle() method

The shuffle() is a built-in method from the java.util.Collections class that randomly reorders the elements of a list. It is a simple and convenient way to shuffle a list, which uses the Fisher–Yates shuffle algorithm. It internally works by creating an intermediary array from the list, shuffling the array and converting the array back into a list. Here is an example of how to use this method:

Download  Run Code

 
There is an overloaded version of the Collections.shuffle() method that allows us to pass a java.util.Random object as a second argument. This way, we can control the randomness of the shuffling process by using a fixed seed or a different random number generator. For instance:

Download  Run Code

That’s all about shuffling an ArrayList in Java.