Languages
[Edit]
EN

Java - get random element from HashSet

0 points
Created by:
Peter-Mortensen
558

In this article, we would like to show you how to get a random element from HashSet in Java.

 

1. Using for loop

Edit

In this example, we generate a random number between 0 and HashSet size. Then we iterate through the HashSet till we reach the element located at the randomNumber position.

Output:

2. Using iterator

Edit

In this example, we generate a random number between 0 and HashSet size. Then using iterator we iterate through the HashSet till we reach the element located at the randomNumber position.

Output:

3. By converting HashSet to Array

Edit

In this example, we convert numbers HashSet into an array and then access the random element from it.

Output:

1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - random numbers

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join