Collection Shuffle in Java
Problem
Collections.shuffle() randomly reorders a List in place — passing it a seeded Random instead of relying on the no-argument overload makes the exact shuffled order reproducible instead of different on every run.
Given a List of integers, randomly reorder it so the same seed always produces the same shuffled order.
Java Program
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionShuffle {
public static void main(String[] args) {
List<Integer> cards = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.shuffle(cards, new Random(42)); // fixed seed makes the result reproducible
System.out.println("Shuffled: " + cards);
}
}Output
Core Logic
Handing shuffle() a Random constructed with a fixed seed makes its 'random' reordering deterministic — the exact same seed always produces the exact same resulting order.
- 1
new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5))builds a resizable list holding the numbers 1 through 5 in order. - 2
Collections.shuffle(cards, new Random(42))reorders the list in place, using the seeded generator to decide every swap. - 3Because the seed is fixed at
42, this exact call produces the exact same resulting order —[2, 3, 4, 5, 1]— every single time it runs. - 4The no-argument overload,
Collections.shuffle(cards), would instead use a freshly-seeded generator each run, producing a different order every time — not suitable for a reproducible example.
[1, 2, 3, 4, 5] with new Random(42) always rearranges it into [2, 3, 4, 5, 1], since the seed fixes every random decision the algorithm makes.Key Point: A seeded Random is what makes this example's output reproducible and testable at all — real-world shuffling (a card game, a playlist) would normally skip the seed and use the no-argument overload for genuine randomness.
Why: Collections.shuffle() performs a single linear-time Fisher-Yates-style pass, swapping each position with a randomly chosen earlier one, with no extra storage beyond the list itself.