Java Collections shuffle() Method
The shuffle() is a Java Collections class method which works by randomly permuting the specified list elements. There is two different types of Java shuffle() method which can be differentiated depending on its parameter. These are:
Java Collections shuffle(list) Method
The shuffle(list) method is used to work by randomly reorders the specified list elements using a default randomness.
Java Collections shuffle(list, random) Method
The shuffle(list, random) method is used to work by randomly reorders the list elements using the specified randomness.
Following is the declaration of shuffle() method:
The shuffle() method does not return anything.
UnsupportedOperationException- This method thrown exception if the specified list or its list-iterator does not support the set operation.
Java 1.5 and above
Example 1Test it Now
List before Shuffle : [A, B, C, D] List after shuffle : [A, C, D, B]
Example 2Test it Now
List before Shuffle : [10, -20, 50, 90, -15] List after shuffle : [10, 50, 90, -15, -20]
Example 3Test it Now
List before Shuffle = [45, 20, 55, 90, 15] Shuffled List with Random() = [45, 55, 15, 90, 20] Shuffled List with Random(3) = [90, 55, 45, 15, 20]
Example 4Test it Now
[one, two, three, four] [four, two, one, three]