The shuffle() method of the Collections class is used to randomly rearrange the elements of a list. It belongs to the java.util package and changes the order of elements in the original list.
- Collections.shuffle() randomly rearranges the elements of a list.
- It can use either the default source of randomness or a user-provided Random object.
Working Of Collections.shuffle()
The shuffle() method randomly permutes the elements of the list.
- It processes the list from the last element toward the beginning.
- At each position, it selects a random element from the remaining portion of the list.
- The selected element is then swapped with the current position.
Syntax
There are two overloaded versions of the shuffle() method.
1. Using Default Randomness:
public static void shuffle(List<?> list)
2. Using User-Provided Randomness:
public static void shuffle(List<?> list, Random rnd)
Example: Shuffle a List using Collections.shuffle()
import java.util.*;
class ShuffleDemo {
public static void main(String[] args)
{
// Create a list
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Mango");
fruits.add("Orange");
fruits.add("Banana");
fruits.add("Grapes");
// Print the original list
System.out.println("Original List: " + fruits);
// Shuffle the list
Collections.shuffle(fruits);
// Print the shuffled list
System.out.println("Shuffled List: " + fruits);
}
}
Output
Original List: [Apple, Mango, Orange, Banana, Grapes] Shuffled List: [Orange, Apple, Mango, Banana, Grapes]
Explanation: The list initially contains five fruits in a fixed order. The Collections.shuffle(fruits) method randomly changes their positions. Since the method uses randomization, the shuffled order may be different each time the program runs.
Example: Shuffle a List Using Random
import java.util.*;
class ShuffleRandomDemo {
public static void main(String[] args)
{
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
numbers.add(40);
numbers.add(50);
System.out.println("Original List: " + numbers);
// Create a Random object with a fixed seed
Random random = new Random(10);
// Shuffle the list using the Random object
Collections.shuffle(numbers, random);
System.out.println("Shuffled List: " + numbers);
}
}
Output
Original List: [10, 20, 30, 40, 50] Shuffled List: [50, 30, 10, 20, 40]
Explanation: The Random object is created with the seed 10 and passed to Collections.shuffle(). Using the same seed produces the same shuffle sequence, making the result useful when a repeatable result is required.