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:

Java Deep Learning Essentials - Yusuke Sugomori
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Spring NoSuchBeanDefinitionException
Từ khóa throw và throws trong Java
Jackson JSON Views
Java Program to Solve Set Cover Problem assuming at max 2 Elements in a Subset
The Spring @Controller and @RestController Annotations
Adding Parameters to HttpClient Requests
Java Program to Represent Graph Using Incidence Matrix
Java Program to Perform Inorder Recursive Traversal of a Given Binary Tree
Mệnh đề Switch-case trong java
A Guide to BitSet in Java
Java Program to Find All Pairs Shortest Path
Spring Data Java 8 Support
How to Count Duplicate Elements in Arraylist
Java Program to Implement Skew Heap
Guide to UUID in Java
The Java 8 Stream API Tutorial
Send email with JavaMail
Java Program to Generate a Graph for a Given Fixed Degree Sequence
Java Program to Implement Regular Falsi Algorithm
Hướng dẫn Java Design Pattern – Bridge
Java Program to Implement Adjacency Matrix
Xử lý ngoại lệ đối với trường hợp ghi đè phương thức trong java
Java Program to Implement Binary Heap
Java Program to find the number of occurrences of a given number using Binary Search approach
Java Program to Implement the String Search Algorithm for Short Text Sizes
Java Program to Implement the RSA Algorithm
A Quick Guide to Spring Cloud Consul
Write/Read cookies using HTTP and Read a file from the internet
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Java Program to Implement Booth Algorithm