Languages
[Edit]
EN

Java - get random element from set

4 points
Created by:
Root-ssh
178260

1. Convert HashSet to ArrayList via constructor

Edit

Example:

Not very efficient because we need to create ArrayList based on HashSet.
So if the set is not too large it's ok solution.

2. Iteration + random number

Edit

Example:

  • Iterate over the set and generate random number within size of the set.
  • Iterate over the elements of the set and keep index
  • If index is equal to the randomly generated index then return element from set.
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 - collections

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