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:
- By converting it to an array
- 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
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 );
Integer[] arrayNumbers = hs.toArray( new Integer[hs.size()]);
Random rndm = new Random();
int rndmNumber = rndm.nextInt(hs.size());
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
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();
int randomNumber = random.nextInt(set.size());
Iterator<? extends E> iterator = set.iterator();
int currentIndex = 0 ;
E randomElement = null ;
while (iterator.hasNext()) {
randomElement = iterator.next();
if (currentIndex == randomNumber)
return randomElement;
currentIndex++;
}
return randomElement;
}
}
|
Output
Random element: 99
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
07 Jan, 2021
Like Article
Save Article