Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to shuffle collection elements.

Java Code Example — Utility Programs

ADVERTISEMENT

Java Program to shuffle collection elements.

Objective

Write a Java program to shuffle elements in a Collection randomly.

Algorithm / Approach

  1. Import java.util.*.
  2. Create an ArrayList and add several numbers to it.
  3. Print the original list.
  4. Call Collections.shuffle(al) and print the list again.
  5. Repeat to show that it produces a different random order every time.
Test.java
import java.util.*;
class Test {
 public static void main(String [] ar)
 {
   ArrayList al = new ArrayList();
   al.add(11);  
   al.add(22);
   al.add(33);
   al.add(44);
   al.add(55);
   al.add(66);
   System.out.println(al);
   Collections.shuffle(al);
   System.out.println(al);
   Collections.shuffle(al);
   System.out.println(al);
   Collections.shuffle(al);
   System.out.println(al);
 }
}

Expected Output

[11, 22, 33, 44, 55, 66]
[66, 55, 33, 11, 44, 22]
[33, 44, 66, 11, 55, 22]
[44, 66, 55, 22, 33, 11]

Explanation of the Program

  • The Collections (plural) class is a utility class filled with static methods that operate on collections.
  • The shuffle() method uses a default source of randomness to randomly permute the specified list, which is highly useful in games (like shuffling a deck of cards or randomizing a quiz).

Complexity

Time Complexity O(n) - Linear time using the Fisher-Yates shuffle algorithm.
Space Complexity O(1) - Modifies the list in-place.
ADVERTISEMENT