Java – Get Random Item/Element From a List

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

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 instancfor different scenarios.

Code examples can be found on GitHub.

Related posts:

Send email with authentication
Java Program to Represent Graph Using Incidence Matrix
A Guide to Concurrent Queues in Java
Spring 5 Testing with @EnabledIf Annotation
Beans and Dependency Injection
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Java Program to Implement HashMap API
Java Program to Implement Sorted Circular Doubly Linked List
SOAP Web service: Upload và Download file sử dụng MTOM trong JAX-WS
Java Program to Implement PriorityQueue API
Java Program to Find the Shortest Path Between Two Vertices Using Dijkstra’s Algorithm
Hướng dẫn sử dụng lớp Console trong java
Java Program to Implement Warshall Algorithm
Jackson – Decide What Fields Get Serialized/Deserialized
Java Program to Implement the Vigenere Cypher
Dockerizing a Spring Boot Application
Using Spring @ResponseStatus to Set HTTP Status Code
How to Use if/else Logic in Java 8 Streams
Java Program to Evaluate an Expression using Stacks
Java Program to Implement Double Ended Queue
Java Program to Generate Random Partition out of a Given Set of Numbers or Characters
Java Program to Find Maximum Element in an Array using Binary Search
Giới thiệu Google Guice – Binding
Java Program to Generate All Pairs of Subsets Whose Union Make the Set
Deque và ArrayDeque trong Java
Guide to the Java Clock Class
Converting Between a List and a Set in Java
Java Program to Implement Quick Hull Algorithm to Find Convex Hull
Sorting Query Results with Spring Data
What is a POJO Class?
New Features in Java 12
Java Program to Find Nearest Neighbor for Dynamic Data Set