Home >Java >javaTutorial >How to Randomly Select an Element from a Java HashSet or LinkedHashSet?
Choosing a random item from a set is a common operation in various programming scenarios. Java offers different types of sets, including HashSet and LinkedHashSet. Let's examine how to perform this task efficiently.
Java's HashSet and LinkedHashSet provide a convenient way to store unique elements. To pick a random element from these sets, you can follow this approach:
<code class="java">int size = myHashSet.size(); int item = new Random().nextInt(size); // Use a shared Random object in practice int i = 0; for (Object obj : myHashSet) { if (i == item) return obj; i++; }</code>
This technique utilizes the following steps:
This approach ensures uniform distribution in selecting a random element from the set while maintaining the set's order in the case of LinkedHashSet.
The above is the detailed content of How to Randomly Select an Element from a Java HashSet or LinkedHashSet?. For more information, please follow other related articles on the PHP Chinese website!