Retrieve a random item from a List in Java
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.util.List; import java.util.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; class Main { public static<T> T getRandomElement(List<T> list) { Random random = new Random(); int randomIndex = random.nextInt(list.size()); return list.get(randomIndex); } public static void main(String[] args) { List<Integer> nums = IntStream.rangeClosed(1, 10) .boxed().collect(Collectors.toList()); int random = getRandomElement(nums); System.out.println(random); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; class Main { public static<T> List<T> getRandomElement(List<T> list, int n) { if (n > list.size()) { throw new IndexOutOfBoundsException(); } List<T> copy = new ArrayList<>(list); Collections.shuffle(copy); return copy.subList(0, n); } public static void main(String[] args) { List<Integer> nums = IntStream.rangeClosed(1, 10) .boxed().collect(Collectors.toList()); int n = 2; List<Integer> random = getRandomElement(nums, n); System.out.println(random); } } |
That’s all about retrieving a random item from a List in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)