java-random-list-element
Java – Get Random Item/Element From a List
1. Introduction
2. Picking a Random Item/Items
In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List.get() method.
The key point here is to remember that you mustn’t use an index that exceeds your List’s capacity.
2.1. Single Random Item
public void givenList_shouldReturnARandomElement() {
List<Integer> givenList = Arrays.asList(1, 2, 3);
Random rand = new Random();
int randomElement = givenList.get(rand.nextInt(givenList.size()));
}
Instead of Random class, you can always use static method Math.random() and multiply it with list size (Math.random() generates Double random value between 0 (inclusive) and 1 (exclusive), so remember to cast it to int after multiplication).
2.2. Select Random Index In Multithread Environment
When writing multithread applications using the single Random class instance, might result in picking same value for every process accessing this instance. We can always create a new instance per thread by using a dedicated ThreadLocalRandom class:
int randomElementIndex
= ThreadLocalRandom.current().nextInt(listSize) % givenList.size();
2.3. Select Random Items With Repetitions
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() {
Random rand = new Random();
List<String> givenList = Arrays.asList("one", "two", "three", "four");
int numberOfElements = 2;
for (int i = 0; i < numberOfElements; i++) {
int randomIndex = rand.nextInt(givenList.size());
String randomElement = givenList.get(randomIndex);
}
}
2.4. Select Random Items Without Repetitions
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() {
Random rand = new Random();
List<String> givenList = Lists.newArrayList("one", "two", "three", "four");
int numberOfElements = 2;
for (int i = 0; i < numberOfElements; i++) {
int randomIndex = rand.nextInt(givenList.size());
String randomElement = givenList.get(randomIndex);
givenList.remove(randomIndex);
}
}
2.5. Select Random Series
public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() {
List<Integer> givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
Collections.shuffle(givenList);
int randomSeriesLength = 3;
List<Integer> randomSeries = givenList.subList(0, randomSeriesLength);
}
3. Conclusion
In this article, we explored the most efficient way of fetching random elements from a List instance for different scenarios.
Code examples can be found on GitHub.