Random Element Selection from a Set
Selecting a random element from a set can be a useful operation in various programming scenarios. In Java, if dealing with a HashSet or a LinkedHashSet specifically, there are a few approaches to consider.
Approach:
The provided solution employs a simple algorithm to achieve this. It involves:
Code Example:
<code class="java">int size = myHashSet.size(); int item = new Random().nextInt(size); // Consider using a shared Random object for efficiency int i = 0; for (Object obj : myHashSet) { if (i == item) { return obj; } i++; }</code>
The above is the detailed content of How to Randomly Select an Element from a HashSet or LinkedHashSet in Java?. For more information, please follow other related articles on the PHP Chinese website!