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 email@example.com. 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
- Java.util.LinkedList.poll(), pollFirst(), pollLast() with examples in Java
- Java lang.Long.highestOneBit() method in Java with Examples
- Java.util.Collections.disjoint() Method in java with Examples
- Java lang.Long.numberOfLeadingZeros() method in Java with Examples
- Java lang.Long.reverse() method in Java with Examples
- Java.util.Collections.rotate() Method in Java with Examples
- Java lang.Long.byteValue() method in Java with Examples
- Java lang.Long.numberOfTrailingZeros() method in Java with Examples
- Java lang.Long.lowestOneBit() method in Java with Examples
- Java.util.BitSet class methods in Java with Examples | Set 2
- Java.util.Arrays.equals() in Java with Examples
- Java.util.BitSet class in Java with Examples | Set 1
- Java Clock tickMinutes() method in Java with Examples
- Java 8 | ArrayDeque removeIf() method in Java with Examples
- Java.util.Collections.frequency() in Java with Examples