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


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.


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.


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.

About the author



rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

Add Comment

Your email address will not be published. Required fields are marked *