java.util.Collections.shuffle() is a java.util.Collections class method.
// Shuffles mylist public static void shuffle(List mylist) This method throws UnsupportedOperationException if the given list or its list-iterator does not support the set operation.
Original List : [code, quiz, geeksforgeeks, quiz, practice, qa] Shuffled List : [qa, quiz, practice, code, quiz, geeksforgeeks]
It shuffles a given list using the user provided source of randomness.
// mylist is the list to be shuffled. // rndm is source of randomness to shuffle the list. public static void shuffle(List mylist, Random rndm) It throws UnsupportedOperationException if the specified list or its list-iterator does not support the set operation.
Original List : [code, quiz, geeksforgeeks, quiz, practice, qa] Shuffled List with Random() : [qa, quiz, geeksforgeeks, code, practice, quiz] Shuffled List with Random(3) : [quiz, code, quiz, practice, qa, geeksforgeeks] Shuffled List with Random(5) : [code, practice, geeksforgeeks, qa, quiz, quiz]
- This method works by randomly permuting the list elements
- Runs in linear time. If the provided list does not implement the RandomAccess interface, like LinkedList and is large, it first copies the list into an array, then shuffles the array copy, and finally copies array back into the list. This makes sure that the time remains linear.
- It traverses the list backwards, from the last element up to the second, repeatedly swapping a randomly selected element into the “current position”. Elements are randomly selected from the portion of the list that runs from the first element to the current position, inclusive. [Source : javadoc]
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.