Home >Java >javaTutorial >How to Pick a Random Element from a HashSet or LinkedHashSet in Java?
Picking a Random Element from a HashSet or a LinkedHashSet in Java
When working with sets, particularly HashSets or LinkedHashSets, the need to select a random element might arise. Here's a detailed explanation of how to achieve this in Java:
The provided solution involves calculating the size of the HashSet, generating a random number within that range, and then iterating through the elements to return the one at the randomly selected index. The following code snippet demonstrates this process:
<code class="java">int size = myHashSet.size(); int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this int i = 0; for (Object obj : myHashSet) { if (i == item) { return obj; } i++; }</code>
By implementing this approach, you can efficiently select a random element from either a HashSet or a LinkedHashSet, providing a convenient solution for your programming needs.
The above is the detailed content of How to Pick a Random Element from a HashSet or LinkedHashSet in Java?. For more information, please follow other related articles on the PHP Chinese website!