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:
- By converting it to an array
- Using an Iterator or a for loop
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.
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.
Random element: 99