Skip to content
Related Articles

Related Articles

Randomly select items from a List in Java
  • Difficulty Level : Medium
  • Last Updated : 08 Mar, 2021

In this article, we will show the most efficient way, finding or picking an element from the List. The basic idea for pick an item from the list is, First generate a number that should be between 0 to list size.

1. Single Random Item

First, we select a random index for using Random.nextInt(int bound) method. Instead of Random class, you can always use the static method Math.random()(random() method generate a number between 0 and 1) and multiply it with list size. 

Java




// Java program select a random element from array
 
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
public class GFG {
 
    // Drive Function
    public static void main(String[] args)
    {
 
        // create a list of Integer type
        List<Integer> list = new ArrayList<>();
        // add 5 element in ArrayList
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
 
        GFG obj = new GFG();
 
        // take a random element from list and print them
        System.out.println(obj.getRandomElement(list));
    }
 
    // Function select an element base on index
    // and return an element
    public int getRandomElement(List<Integer> list)
    {
        Random rand = new Random();
        return list.get(rand.nextInt(list.size()));
    }
}
Output
30

2. Select Random Index In Multithread Environment 



When we work with multithread applications using the single Random class instance then might result in picking the same value for every process accessing this instance. Hence, We can always create a new instance per thread by using ThreadLocalRandom class. 

Java




// Java program select a random element from List
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
 
public class GFG {
 
    // Drive Function
    public static void main(String[] args)
    {
 
        // create a list of Integer type
        List<Integer> list = new ArrayList<>();
 
        // add 5 element in ArrayList
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
 
        GFG obj = new GFG();
 
        // boundIndex to select in sub list
        int boundIndex = 3;
 
        // take a random element from list and print it
        System.out.println(
            obj.getRandomElement(list, boundIndex));
    }
 
    // Function to select an element based on index and
    // return an element
    public int getRandomElement(List<Integer> list,
                                int bound)
    {
        // ThreadLocalRandom generates an int type number
        return list.get(
            ThreadLocalRandom.current().nextInt(list.size())
            % bound);
    }
}
Output
10

3. Select Random Items With Repetitions List Element 

Sometimes we want to pick a few elements from a list. So first know how much element we want to select after that we select items one by one and add a new list and return it. Note: in this case, one element may be select many times because we are not remove selected elements so the list size remaining the same.

Java




// Java program select a random element from List
 
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
public class GFG {
 
    // Drive Function
    public static void main(String[] args)
    {
 
        // create a list of Integer type
        List<Integer> list = new ArrayList<>();
 
        // add 5 element in ArrayList
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
 
        GFG obj = new GFG();
 
        // boundIndex for select in sub list
        int numberOfElements = 3;
 
        // take a random element from list and print them
        System.out.println(
            obj.getRandomElement(list, numberOfElements));
    }
 
    // Function select an element base on index and return
    // an element
    public List<Integer>
    getRandomElement(List<Integer> list, int totalItems)
    {
        Random rand = new Random();
 
        // create a temporary list for storing
        // selected element
        List<Integer> newList = new ArrayList<>();
        for (int i = 0; i < totalItems; i++) {
 
            // take a raundom index between 0 to size
            // of given List
            int randomIndex = rand.nextInt(list.size());
 
            // add element in temporary list
            newList.add(list.get(randomIndex));
        }
        return newList;
    }
}
Output
[40, 20, 40]

4. Select Random Items Without Repetitions List Element 

Sometimes we want to pick a few elements from a list. So first make sure how much element we want to select after that we select items one by one and add a new list and return it. Note: in this case, one element selects only ones because we are remove selected elements, so decrease list size also automatic by JVM.

Java




// Java program select a random element from List
 
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
public class GFG {
 
    // Drive Function
    public static void main(String[] args)
    {
 
        // create a list of Integer type
        List<Integer> list = new ArrayList<>();
        // add 5 element in ArrayList
        list.add(10);
        list.add(20);
        list.add(30);
        list.add(40);
        list.add(50);
 
        GFG obj = new GFG();
 
        // boundIndex for select in sub list
        int numberOfElements = 3;
 
        // take a random element from list and print them
        System.out.println(
            obj.getRandomElement(list, numberOfElements));
    }
 
    // Function select an element base on index and return
    // an element
    public List<Integer>
    getRandomElement(List<Integer> list, int totalItems)
    {
        Random rand = new Random();
 
        // create a temporary list for storing
        // selected element
        List<Integer> newList = new ArrayList<>();
        for (int i = 0; i < totalItems; i++) {
 
            // take a raundom index between 0 to size
            // of given List
            int randomIndex = rand.nextInt(list.size());
 
            // add element in temporary list
            newList.add(list.get(randomIndex));
 
            // Remove selected element from orginal list
            list.remove(randomIndex);
        }
        return newList;
    }
}
Output
[50, 10, 20]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :