This post will discuss how to retrieve a random item from a List in Java.

1. Using Random.nextInt() method

The Random’s nextInt() method returns a pseudo-random value between 0 (inclusive) and the specified value (exclusive).

The idea is to use the Random.nextInt() method to generate a random index less than the list’s size and use that index to return the random value. The usage is demonstrated below:

Download  Run Code

2. Using Collections.shuffle() method

If your requirement is to get multiple distinct random values from the list, the better solution is to use the Collections.shuffle() method on the list. This approach, however, changes the original order of elements in the list. To avoid any modifications to the original list, call the shuffle method on the list’s copy.

Download  Run Code

That’s all about retrieving a random item from a List in Java.