Home > Java > javaTutorial > body text

How to Pick a Random Element from a HashSet or LinkedHashSet in Java?

Mary-Kate Olsen
Release: 2024-10-28 13:06:30
Original
479 people have browsed it

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!