This example shows how to get random elements from HashSet in Java. This example also shows how to get random elements from Java HashSet using an iterator, for loop, and by converting it to an array.
How to get random elements from HashSet in Java?
Unlike List classes (for e.g. ArrayList or LinkedList), 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.
However, there a couple of ways using which we can get that.
1. 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; public class HashSetGetRandomElementsExample { public static void main(String[] args) { Set<Integer> hSetNumbers = new HashSet<Integer>(); hSetNumbers.add(1); hSetNumbers.add(2); hSetNumbers.add(3); hSetNumbers.add(4); hSetNumbers.add(5); hSetNumbers.add(6); hSetNumbers.add(7); hSetNumbers.add(8); hSetNumbers.add(9); hSetNumbers.add(10); System.out.println("Random element: " + getRandomElement(hSetNumbers)); } private static <E> E getRandomElement(Set<? extends E> set){ /* * Generate a random number using nextInt * method of the Random class. */ Random random = new Random(); //this will generate a random number between 0 and HashSet.size - 1 int randomNumber = random.nextInt(set.size()); //get an iterator 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
1 |
Random element: 6 |
The code will get a new random element from the HashSet object each time it is executed.
You can also use an enhanced for loop instead of the Iterator as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
private static <E> E getRandomElement(Set<? extends E> set){ Random random = new Random(); int randomNumber = random.nextInt(set.size()); int currentIndex = 0; E randomElement = null; for(E element : set){ randomElement = element; if(currentIndex == randomNumber) return randomElement; currentIndex++; } return randomElement; } |
Output
1 |
Random element: 9 |
2. By converting to an array
We can also convert HashSet to an array and then access the random element from it using an index as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
Set<Integer> hSetNumbers = new HashSet<Integer>(); hSetNumbers.add(1); hSetNumbers.add(2); hSetNumbers.add(3); hSetNumbers.add(4); hSetNumbers.add(5); hSetNumbers.add(6); hSetNumbers.add(7); hSetNumbers.add(8); hSetNumbers.add(9); hSetNumbers.add(10); //convert HashSet to an array Integer[] arrayNumbers = hSetNumbers.toArray( new Integer[ hSetNumbers.size() ] ); //generate a random number Random random = new Random(); //this will generate a random number between 0 and HashSet.size - 1 int randomNumber = random.nextInt(hSetNumbers.size()); //get the element at random number index from the array System.out.println("Random element: " + arrayNumbers[randomNumber]); |
Output
1 |
Random element: 4 |
Which method should I use?
If the size of the HashSet object is too large, both of the approaches are slow. Converting HashSet to an array needs to allocate a new array first which is a costly operation in terms of performance. On the other hand, iterating over HashSet is a slow operation if done frequently.
We need to choose the best approach based on our requirements. Use the iteration approach if the set is small in size, is frequently updated and we need to get random elements very few times.
Use the array approach if the HashSet is going to stay unchanged and we need to fetch random elements many times. The array allocation is costly but it is one time operation which can be justified if we want to pick random elements many times.
This example is a part of the HashSet in Java Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 HashSet