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.

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