Home > Java > javaTutorial > body text

How to Randomly Select an Element from a HashSet or LinkedHashSet in Java?

DDD
Release: 2024-10-29 03:11:30
Original
760 people have browsed it

How to Randomly Select an Element from a HashSet or LinkedHashSet in Java?

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:

  1. Determining the size of the set (size) using the size() method.
  2. Generating a random integer (item) within the range [0, size-1] using nextInt(size).
  3. Iterating through the set, keeping track of the current index (i)
  4. When i matches the randomly generated item, the corresponding object is returned.

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template