Skip to content

Get Random Elements from Java HashSet Example

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.

Output

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.

Output

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.

Output

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

About the author

Leave a Reply

Your email address will not be published.