Java Example – Shuffling a Collection
The following example demonstrates how to use the Collections.shuffle() method of the Collections class to shuffle the order of collection elements:
Main.java File
import
java
.
util
.*;
public
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
List
<
Integer
list
=
new
ArrayList
<
Integer
(
);
for
(
int
i
=
0
;
i
<
10
;
i
++
)
list
.
add
(
new
Integer
(
i
)
)
;
System
.
out
.
println
(
"
Before shuffling:
"
)
;
System
.
out
.
println
(
list
)
;
for
(
int
i
=
1
;
i
<
6
;
i
++
)
{
System
.
out
.
println
(
"
The
"
i
"
th shuffle:
"
)
;
Collections
.
shuffle
(
list
)
;
System
.
out
.
println
(
list
)
;
}
}
}
The output of the above code is:
Before shuffle:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
First shuffle:
[2, 0, 5, 1, 4, 9, 7, 6, 3, 8]
Second shuffle:
[2, 6, 4, 8, 5, 7, 9, 1, 0, 3]
Third shuffle:
[6, 5, 1, 0, 3, 7, 2, 4, 9, 8]
4th shuffle:
[1, 3, 8, 4, 7, 2, 0, 6, 5, 9]
5th shuffle:
[3, 0, 7, 9, 5, 8, 4, 2, 1, 6]
Java Examples