Open In App

How to Get Random Elements from Java HashSet?

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.






// 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




// 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

Article Tags :