"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Detailed explanation of Java HashSet/LinkedHashSet random element acquisition method

Detailed explanation of Java HashSet/LinkedHashSet random element acquisition method

Posted on 2025-03-12
Browse:617

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:

import java.util.Random;
import java.util.Set;

public class RandomSetElement {

    public static void main(String[] args) {
        // Create a HashSet
        Set 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  ;
        }
    }
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3