Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Get Random Elements from Java HashSet?

  • Last Updated : 07 Jan, 2021

Unlike List classes, the HashSet class does not provide any methods using which we can get the elements using their index. It makes it difficult to get random elements from it using the index.

We need to get random elements from HashSet, which can be done by either of the two ways:

  1. By converting it to an array
  2. Using an Iterator or a for loop

Example:

Input:


hs.add(11);
hs.add(24);
hs.add(34);
hs.add(43);
hs.add(55);
hs.add(66);
hs.add(72);
hs.add(80);
hs.add(99);


Output:

Random element: 99

Method 1: By converting to an array.

  • Firstly convert HashSet into an array and then access the random element from it.
  • Then we will create an object of Random class and will call the nextInt() method of that class which will give us any random number less than or equal to the size of the HashSet.
  • And then using an array we will simply print the element present at that index.

Java




// Java program to get random elements from HashSet
// using an array
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // creating the HashSet
        Set<Integer> hs = new HashSet<Integer>();
  
        hs.add(11);
        hs.add(24);
        hs.add(34);
        hs.add(43);
        hs.add(55);
        hs.add(66);
        hs.add(72);
        hs.add(80);
        hs.add(99);
  
        // convert HashSet to an array
        Integer[] arrayNumbers = hs.toArray(new Integer[hs.size()]);
  
        // generate a random number
        Random rndm = new Random();
  
        // this will generate a random number between 0 and
        // HashSet.size - 1
        int rndmNumber = rndm.nextInt(hs.size());
  
        // get the element at random number index
        System.out.println("Random element: "
                           + arrayNumbers[rndmNumber]);
    }
}
Output
Random element: 11

Method 2: Using an Iterator or a for loop

  • In order to get random elements from the HashSet object, we need to generate a random number between 0 (inclusive) and the size of the HashSet (exclusive).
  • And then iterate through the set till we reach the element located at the random number position as given below.
  • In this approach, we will get the element at a random index using an Iterator.

Java




// Java program to get random elements from HashSet
// using an Iterator
  
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        Set<Integer> hs = new HashSet<Integer>();
  
        hs.add(11);
        hs.add(24);
        hs.add(34);
        hs.add(43);
        hs.add(55);
        hs.add(66);
        hs.add(72);
        hs.add(80);
        hs.add(99);
  
        System.out.println("Random element: "
                           + getRandomElement(hs));
    }
  
    private static <E>
        E getRandomElement(Set<? extends E> set)
    {
  
        Random random = new Random();
  
        // Generate a random number using nextInt
        // method of the Random class.
        int randomNumber = random.nextInt(set.size());
  
        Iterator<? extends E> iterator = set.iterator();
  
        int currentIndex = 0;
        E randomElement = null;
  
        // iterate the HashSet
        while (iterator.hasNext()) {
  
            randomElement = iterator.next();
  
            // if current index is equal to random number
            if (currentIndex == randomNumber)
                return randomElement;
  
            // increase the current index
            currentIndex++;
        }
  
        return randomElement;
    }
}
Output
Random element: 99

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!