Home page

Wednesday, June 14, 2023

HashSet in JAVA

A HashSet in Java is a data structure that represents an unordered collection of unique elements. It is implemented using a hash table, which provides constant-time complexity for the basic operations (add, remove, contains), assuming a good hash function.

You can use a HashSet in situations where you need to store a collection of unique elements and order is not important. Some common use cases for HashSet include:

Removing duplicates: If you have a collection of elements where you want to eliminate duplicate entries, a HashSet can be used. It ensures that each element is unique in the set.

Efficient membership testing: If you frequently need to check whether an element is present in a collection, a HashSet can provide fast membership testing due to its hashing-based implementation.

Here's an example of how you can use a HashSet in Java:

import java.util.HashSet;

public class HashSetExample {

    public static void main(String[] args) {

        HashSet<String> set = new HashSet<>();

        // Adding elements to the HashSet

        set.add("Apple");

        set.add("Banana");

        set.add("Orange");

        set.add("Apple"); // Duplicate entry, will be ignored

        // Iterating over the elements in the HashSet

        for (String element : set) {

            System.out.println(element);

        }

        // Checking if an element exists in the HashSet

        boolean containsBanana = set.contains("Banana");

        System.out.println("Contains Banana? " + containsBanana);

        // Removing an element from the HashSet

        boolean removed = set.remove("Orange");

        System.out.println("Removed Orange? " + removed);

        // Size of the HashSet

        System.out.println("Size of HashSet: " + set.size());

    }

}

In this example, we create a HashSet called set to store strings.

We add elements to the set using the add() method. Note that the duplicate entry of "Apple" is ignored, as HashSet does not allow duplicate elements.

We iterate over the elements of the set using a for-each loop and print each element.

We check if an element exists in the set using the contains() method.

We remove an element from the set using the remove() method and store the result in a boolean variable.

Finally, we print the size of the set using the size() method.

Output:
Apple
Banana
Orange
Contains Banana? true
Removed Orange? true
Size of HashSet: 2

No comments:

Post a Comment