Skip to content

Java ArrayList shuffle elements example

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

How to shuffle elements of ArrayList?

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

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

Java ArrayList shuffle example

Output

How to shuffle two ArrayList in the same sequence?

Imagine that you have two ArrayList objects, one contains the keys and the second ArrayList contains 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 the same randomness? Well, in this case, use the 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 the same randomness.

This example is a part of the Java ArrayList tutorial.

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

About the author

Leave a Reply

Your email address will not be published.