I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE COURSE

1. Introduction

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.

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

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).

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

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);
    }
}

2.4. Select Random Items Without Repetitions

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);
    }
}

2.5. Select Random Series

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);
}

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.

I just announced the new Spring Boot 2 material, coming in REST With Spring:

>> CHECK OUT THE LESSONS