Java HashSet

h‮‬ttps://www.theitroad.com

In Java, a HashSet is a collection class that implements the Set interface, which uses a hash table for storage. The HashSet class is part of the java.util package and provides many useful methods for working with sets of data.

A HashSet is an unordered collection of unique elements. It does not allow duplicate elements, and it does not guarantee the order of the elements in the set. Elements can be added, removed, and searched in constant time, which makes HashSet a very efficient collection for large sets of data.

Here is an example of how to use a HashSet in Java:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        // Creating a HashSet
        HashSet<String> set = new HashSet<>();

        // Adding elements to the HashSet
        set.add("Apple");
        set.add("Banana");
        set.add("Orange");
        set.add("Grapes");

        // Printing the HashSet
        System.out.println("HashSet: " + set);

        // Removing an element from the HashSet
        set.remove("Banana");

        // Printing the HashSet after removing an element
        System.out.println("HashSet after removing an element: " + set);

        // Checking if an element is present in the HashSet
        boolean isPresent = set.contains("Apple");
        System.out.println("Is Apple present in the HashSet? " + isPresent);

        // Checking the size of the HashSet
        int size = set.size();
        System.out.println("Size of the HashSet: " + size);

        // Clearing the HashSet
        set.clear();
        System.out.println("HashSet after clearing: " + set);
    }
}

Output:

HashSet: [Orange, Grapes, Banana, Apple]
HashSet after removing an element: [Orange, Grapes, Apple]
Is Apple present in the HashSet? true
Size of the HashSet: 3
HashSet after clearing: []