Collections

Java ArrayList shuffle elements example

Java ArrayList shuffle elements example shows how to shuffle elements of ArrayList in Java. Example also shows how to shuffle ArrayList using Random seed using Collections class.

How to shuffle elements of ArrayList?

To shuffle elements of ArrayList, use shuffle method of Collections class.

This method shuffles ArrayList using default source of randomness. Internally, it iterates the List in backward direction till second element and swaps the random element to the current position.

Java ArrayList shuffle example

Output

How to shuffle two ArrayList in same sequence?

Imagine that you have two ArrayList objects, one stores the keys and second stores the corresponding values. How to shuffle keys and still be able to retrieve corresponding values from the second list? Consider below given example.

Output

As you can see from the output, key value pairs are no longer in the same order after shuffling them. How to shuffle two ArrayList using same randomness? Well, in this case use overloaded shuffle method which accepts Random as a parameter.

Output

As you can see from the output, now both the List objects are shuffled using same randomness.

Please let us know your views in the comments section below.

Join 1000+ fellow learners! Enter your email address below: