Course contentsShow
← Java
Lesson 1231 of 2,87028. Collections Utility ClassFree lesson

Collections.shuffle: Randomizing List Order

See how shuffle randomizes list elements using the Fisher-Yates algorithm for uniform distribution.

Collections.shuffle: Randomizing List Order

What you'll learn: You'll discover how Collections.shuffle randomizes the elements in a list for uniform, unpredictable ordering.

What Is shuffle?

Collections.shuffle is a utility method that randomly reorders all elements in a list, like shuffling a deck of cards. Each possible arrangement has an equal chance of occurring, making it perfect for games, testing with random data, or any scenario where you need unpredictable order.

How shuffle Works

The method uses the Fisher-Yates algorithm (also called the Knuth shuffle), which guarantees uniform distribution—every permutation of your list is equally likely. Here's the clever idea:

  1. Start at the last element
  2. Pick a random position from 0 to current position
  3. Swap the current element with the randomly chosen one
  4. Move to the previous element and repeat

This single pass through the list achieves perfect randomization.

Basic Usage

import java.util.*;

List<String> deck = new ArrayList<>(Arrays.asList(
    "Ace", "King", "Queen", "Jack", "10"
));

Collections.shuffle(deck);
System.out.println(deck); // Random order, e.g., [Queen, Ace, 10, King, Jack]

Collections.shuffle(deck);
System.out.println(deck); // Different random order

Providing a Custom Random Source

For reproducible "randomness" (useful in testing), pass your own Random instance:

Random seededRandom = new Random(42); // Fixed seed
Collections.shuffle(deck, seededRandom);
System.out.println(deck); // Same "random" order every time with seed 42

Analogy: Think of a card dealer shuffling a deck. shuffle ensures no card is more likely to end up in any particular position—it's fair and truly random (or pseudo-random with a seed).

Key Takeaway: Collections.shuffle uses the Fisher-Yates algorithm to randomize list order with uniform distribution, perfect for games, testing, and scenarios requiring unpredictable element arrangement.