Javatpoint Logo
Javatpoint Logo

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:

  1. Java Collections shuffle(list) Method
  2. 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

Test it Now

Output:

List before Shuffle : [A, B, C, D]
List after shuffle : [A, C, D, B]

Example 2

Test it Now

Output:

List before Shuffle : [10, -20, 50, 90, -15]
List after shuffle : [10, 50, 90, -15, -20]

Example 3

Test it Now

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

Test it Now

Output:

[one, two, three, four]
[four, two, one, three]






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA