Java Collections shuffle()

In this guide, you will learn about the Collections shuffle() method in Java programming and how to use it with an example.

1. Collections shuffle() Method Overview


The shuffle() method of the Collections class in Java is used to randomly permute the elements in a specified list.


Collections.shuffle(List<?> list)


list: The list whose elements are to be shuffled.

Key Points:

- This method uses a default source of randomness which is suitable for informal purposes.

- It throws UnsupportedOperationException if the specified list or its list-iterator doesn't support the set operation.

- For more controlled randomness, there is an overloaded shuffle() method that allows the user to specify a Random object.

2. Collections shuffle() Method Example

import java.util.*;

public class CollectionsShuffleExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

        // Shuffling the list
        System.out.println("Shuffled list: " + numbers);


Shuffled list: [3, 1, 5, 2, 4]  // Note: The output will vary as the list is shuffled randomly.


In the provided example, we create a list of integers from 1 to 5. We then use the shuffle() method to randomly rearrange the order of its elements and print the shuffled list.