In game development (like card games) or content recommendation algorithms (like generating a random music playlist), we need to randomize the order of elements in a collection. Java's Collections framework provides a built-in utility method for this: **Collections.shuffle(List<?> list)**.
This method runs in linear time O(N), swapping elements randomly from back to front using the Fisher-Yates shuffle algorithm under the hood.
Imagine you have a deck of playing cards stacked in perfect numerical order: A, 2, 3, 4, 5...
To prepare the game, you throw the cards into a **tumbling drum machine (Collections.shuffle)**. The machine rotates, spinning and scrambling the cards in random directions. When the machine stops and you pull them out, the deck is completely randomized, giving you a fair and unpredictable sequence (e.g. 3, A, 5, 2, 4).
Java Implementation
Below, we load a list of custom Song objects and randomize their playback order using Collections.shuffle:
package io.practise;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class ShufflingSong {
public static void main(String[] args) {
Song song1 = new Song("A");
Song song2 = new Song("B");
Song song3 = new Song("C");
Song song4 = new Song("D");
Song song5 = new Song("E");
List<Song> playlist = Arrays.asList(song1, song2, song3, song4, song5);
System.out.println("Original Playlist: " + playlist);
// Shuffle the list in-place
Collections.shuffle(playlist);
System.out.println("Shuffled Playlist: " + playlist);
}
}
class Song {
String name;
public Song(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Song{name='" + name + "'}";
}
}
Conclusion
The `Collections.shuffle()` method modifies the target list in-place. If you want to retain the original order of the list, copy the list first before invoking the shuffle command.