Collections

Java ArrayList get random elements example

Java ArrayList get random elements example shows how to get random element from ArrayList in Java. Example also shows how to get random item from ArrayList using various approaches.

How to get random element from ArrayList in Java?

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

1) Get random element from ArrayList using Random class

You can use nextInt method of Random class to generate 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 random number and use that as index in get method of ArrayList.

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 threads 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

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

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

About the author

rahimv

rahimv

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 *