103
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
- Java Collections shuffle(list, random) Method
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.
Syntax
Following is the declaration of shuffle() method:
Parameter
Parameter | Description | Required/Optional |
---|---|---|
list | It is the list which will be shuffled. | Required |
random | It is the source of randomness which is used to shuffle the list. | Required |
Returns
The shuffle() method does not return anything.
Exceptions
UnsupportedOperationException– This method thrown exception if the specified list or its list-iterator does not support the set operation.
Compatibility Version
Java 1.5 and above
Example 1
Output:
List before Shuffle : [A, B, C, D] List after shuffle : [A, C, D, B]
Example 2
Output:
List before Shuffle : [10, -20, 50, 90, -15] List after shuffle : [10, 50, 90, -15, -20]
Example 3
Output:
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 4
Output:
[one, two, three, four] [four, two, one, three]
Next TopicJava Collections Class