How to randomly select items from a list in Java

In this tutorial, we will learn how to randomly select items from a list in Java. A list in Java is an interface that is present in the util package and inherits the collection interface. In a list, we can store data like we do in array but the list is variable length whereas array is fixed length. List can only store objects and allows sequential access only.

Ways to select items in a list randomly

Below, you can see three different ways to randomly select items from a list:

1. To select one random item only:

The very first way anyone can think of is using an object of random class and using its nextInt() member function. So our first approach would be that only. So let’s understand how nextInt() works, the arguments to nextInt() is the size of our list and it randomly generates an index between those bounds, and the element present at that index will be chosen by our program.

Code for this approach:

import java.util.ArrayList; 
import java.util.List; 
import java.util.Random; 
import java.util.Arrays;
  
public class RandomItem { 
  
    public static void main(String[] args) 
    { 
  
        // create a list of Integer type 
        List<Integer> list = new ArrayList<>(Arrays.asList(10,20,30,40,50)); 
        int result;
        Random rand = new Random(); 
        result = list.get(rand.nextInt(list.size()));  //store item in result
        
        // print the selected item.
        System.out.println("selected random item is " + result);
    }

}

Output:

selected random item is 50

2. To select more than one random item with repetition:

There can be a situation when the user wants to select more than one random item, so his normal approach will be generating a random index using the nextInt() function of random class’s object and looping it till we get the desired number of elements. But in this case, the random index generated can be the same and there are possibilities of getting the same random items chosen again and again. Here, is a code depicting the same situation:

import java.util.ArrayList; 
import java.util.List; 
import java.util.Random; 
import java.util.Arrays;
  
public class RandomItem { 
  
    // main function
    public static void main(String[] args) 
    { 
  
        // create a list of Integer values.
        List<Integer> list = new ArrayList<>(Arrays.asList(10,20,30,40,50,60,70,80)); 
  
        RandomItem randomItem = new RandomItem(); //create an instance of class 
  
        // number of elements to be selected.
        int numberOfElements = 4; 
  
        // printing random selected elements.
        System.out.println("random selected items are " + randomItem.getRandomElement(list,numberOfElements)); 
    } 
  
    // Function to select random elements.
    public List<Integer> getRandomElement(List<Integer> list,int totalItems) 
    { 
        Random rand = new Random(); // object of Random class.
  
       //temprory list to hold selected items.
        List<Integer> tempList = new ArrayList<>(); 
        for (int i = 0; i < totalItems; i++) { 
            int randomIndex = rand.nextInt(list.size());
            tempList.add(list.get(randomIndex)); 
        } 
        return tempList; 
    } 
}

Output:

random selected items are [30, 50, 50, 60]

3. To select more than one item without repetition:

Now, from the above code, we realize that there are chances a user ends up getting the same random item chosen more than one time. So, in order to prevent that from happening, we will perform simple while loop checks every time the random index is generated. We will check whether the element at the random index in the list is present in our temporary list or not, if it is present, we will generate a new random index and if it is not present we will break our loop. Here is a program to depict the above-explained situation and its solution:

import java.util.ArrayList; 
import java.util.List; 
import java.util.Random; 
import java.util.Arrays;
  
public class RandomItem { 
  
    // main function
    public static void main(String[] args) 
    { 
  
        // create a list of Integer values.
        List<Integer> list = new ArrayList<>(Arrays.asList(10,20,30,40,50,60,70,80)); 
  
        RandomItem randomItem = new RandomItem(); //create an instance of class 
  
        // number of elements to be selected.
        int numberOfElements = 4; 
  
        // printing random selected elements.
        System.out.println("random selected items are " + randomItem.getRandomElement(list,numberOfElements)); 
    } 
  
    // Function to select random elements.
    public List<Integer> getRandomElement(List<Integer> list,int totalItems) 
    { 
        Random rand = new Random(); // object of Random class.
  
       //temprory list to hold selected items.
        List<Integer> tempList = new ArrayList<>(); 
        for (int i = 0; i < totalItems; i++) { 
            int randomIndex = rand.nextInt(list.size());
            // the loop check on repetition of elements
            while(tempList.contains(list.get(randomIndex))){
                randomIndex = rand.nextInt(list.size());
            }
            tempList.add(list.get(randomIndex)); 
        } 
        return tempList; 
    } 
}

Output:

random selected items are [50, 80, 60, 30]

Hence, this is the way to randomly select items in a list in Java with three cases explained. I hope you find this tutorial helpful.

Thank you.

For more tutorials, visit: Average value of an ArrayList in Java

Leave a Reply

Your email address will not be published. Required fields are marked *