Skip to content

Java ArrayList get random elements example

Java ArrayList get random elements example shows how to get random elements from ArrayList in Java. The example also shows how to get a random value from the ArrayList using various approaches.

How to get random elements from ArrayList in Java?

There are several ways using which you can get a random element from ArrayList as given below.

1) Get random element from ArrayList using the Random class

You can use nextInt method of Random class to generate a random number between 0 and size of the ArrayList and get element at the generated random index as given below.

Output

2) Get random element from ArrayList using Math.random

You can use random method of Math class to generate a random number and use that as an index in the get method of the ArrayList class.

Output

3) Get random element from ArrayList using ThreadLocalRandom (JDK 7 and above)

If you are using multithreading, it is better to use ThreadLocalRandom instead of Random class to generate the random numbers per thread for performance reasons.

Output

4) Get random element from ArrayList using ArrayList shuffle

Another approach to get random items from ArrayList is to shuffle ArrayList and get the elements from it as given below.

Output

This example is a part of the Java ArrayList tutorial.

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

About the author

4 comments

  1. I think there will be a possibly error on option 2 cause it will give you a random between 0 and size of the list and the last index of the list is size() -1

    1. Hello Diego,

      Thanks for your comment. The random method generates a random number that is greater than or equal to 0 and always less than 1 (i.e. 0 <= number < 1). Thus, when we convert the multiplication to an int value, as I have done in the example, it will end up being 1 less than the size specified. For example, if the list size is 5 and the random number is 0.9999, the multiplication will be 5 * 0.9999 = 4.9995. When we convert it to an int, we get 4. I hope it clears your doubts.

  2. Note: Each time the Math.random() method is called it generates a new random value however original order of elements in the ArrayList does not get disturbed.

Leave a Reply

Your email address will not be published.