
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Picking a random List element is a very basic operation but not so obvious to implement. In this article, we’ll show the most efficient way of doing this in different contexts.
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 size.
In order to select a random index, you can use Random.nextInt(int bound) method:
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).
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();
Sometimes you might want to pick few elements from a list. It is quite straightforward:
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);
}
}
Here, you need to make sure that element is removed from the list after selection:
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);
}
}
In case you would like to obtain random series of elements, Collections utils class might be handy:
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);
}
In this article, we explored the most efficient way of fetching random elements from a List instance for different scenarios.