Home > Java > javaTutorial > body text

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

Susan Sarandon
Release: 2024-10-28 05:53:02
Original
410 people have browsed it

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

Finding a Random Element in a Set

In programming, it can be useful to select a random element from a collection, such as a set. Java provides multiple types of sets, including HashSet and LinkedHashSet. This article will explore how to pick a random element from these specific set implementations.

Java's HashSet and LinkedHashSet

A HashSet represents a collection of unique elements and utilizes hashing for fast lookups. A LinkedHashSet maintains the order in which elements were added to the set.

Selecting a Random Element

To select a random element from a set in Java, one can use the following technique:

<code class="java">import java.util.Random;
import java.util.Set;

public class RandomSetElement {

    public static void main(String[] args) {
        // Create a HashSet
        Set<String> myHashSet = new HashSet<>();
        myHashSet.add("One");
        myHashSet.add("Two");
        myHashSet.add("Three");

        // Create a Random object
        Random random = new Random();

        // Calculate the size of the set
        int size = myHashSet.size();

        // Generate a random index
        int item = random.nextInt(size);

        // Iterate through the set to find the element at the random index
        int i = 0;
        for (Object obj : myHashSet) {
            if (i == item) {
                // Return the random element
                System.out.println("Random element: " + obj);
                break;
            }
            i++;
        }
    }
}</code>
Copy after login

In this example, we import the necessary Java libraries and create a HashSet. We then generate a random index between 0 and the size of the set, and iterate through the set using a for-each loop to find and print the element at that index.

The above is the detailed content of How to Pick a Random Element from a Java HashSet or LinkedHashSet?. 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!