Java ProgramsCollectionsCollection Shuffle

Collection Shuffle in Java

beginner·  Collections  ·  Collections Utility

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.

Input
[1, 2, 3, 4, 5], seed = 42
Output
Shuffled: [2, 3, 4, 5, 1]

Java Program

Java
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

Shuffled: [2, 3, 4, 5, 1]

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.

How It Works
  1. 1new ArrayList&lt;&gt;(Arrays.asList(1, 2, 3, 4, 5)) builds a resizable list holding the numbers 1 through 5 in order.
  2. 2Collections.shuffle(cards, new Random(42)) reorders the list in place, using the seeded generator to decide every swap.
  3. 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.
  4. 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.
Shuffling [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.

Complexity
Time Complexity: O(n)Space Complexity: O(1)

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.

Key Concepts

Collections.shuffle()seeded Randomin-place reordering

Related Programs