Java Collections shuffle()

🎓 Check Out My Top 25 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare

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

Definition:

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

Syntax:

Collections.shuffle(List<?> list)

Parameters:

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
        Collections.shuffle(numbers);
        System.out.println("Shuffled list: " + numbers);
    }
}

Output:

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

Explanation:

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.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare