HashSet

What is HashSet in Java

Java’s HashSet is a collection that carries out the Set interface. It stores unique elements using a hash table. Elements are not stored in a specific order, and duplicate values are automatically discarded. HashSet offers constant-time performance for basic operations like adding, removing, and checking for element existence, making it an efficient choice for dealing with unique data in Java.

What are the features of a HashSet in Java?

  1. Unique Elements: HashSet ensures that it stores only unique elements. Duplicate elements are automatically eliminated.
  2. Fast Operations: HashSet provides fast insertion, deletion, and retrieval of elements due to its hashing mechanism.
  3. No Specific Order: Elements in a HashSet have no defined order, and they are not stored based on their insertion order.
  4. Backed by HashMap: HashSet is internally implemented using a HashMap, where elements are stored as keys, and the corresponding values are dummy objects.
  5. Null Values: HashSet allows storing a single null value, as it permits one null key in its underlying HashMap.
  6. Unpredictable Iteration Order: The iteration order of elements in a HashSet may not be predictable or consistent across different runs.
  7. Not Thread-Safe: HashSet is not synchronized and is not thread-safe. If multiple threads modify it concurrently, it must be externally synchronized.
  8. Implements Set Interface: HashSet is a class that implements the Set interface, providing set-based operations like union, intersection, and difference.
  9. Resizable: HashSet automatically resizes itself when the number of elements reaches a threshold to maintain a low load factor, optimizing performance.
  10. Offers Add/Remove Operations: You can add elements using the add() method and remove elements using the remove() method in a HashSet.

Syntax of HashSet

import java.util.HashSet;

HashSet setName = new HashSet<>();

//Syntax for declaring a HashSet with a specific data type

HashSet <Integer> numberSet = new HashSet<>();

//Example: Declaring a HashSet of integers

Explanation:

  1. Import the HashSet class from the util package to use it in your code.
  2. Use the generic syntax to specify the data type of elements that the HashSet will hold within the angle brackets (<>).
  3. Create an instance of the HashSet using the new keyword followed by the HashSet constructor without any arguments.

In the example, we declared a HashSet named numberSet, which will store integers.

Categorized HashSet methods in Java based on their operations.

  1. Adding Elements:
    • add(E element): Adds the specified element to the HashSet if it is not already present.
  2. Removing Elements:
    • remove(Object object): Removes the specified element from the HashSet if it is present.
    • clear(): Removes all elements from the HashSet, making it empty.
  3. Checking Element Existence:
    • contains(Object object): Checks if the HashSet contains the specified element.
    • isEmpty(): Checks if the HashSet is empty.
  4. Size and Status:
    • size(): Returns the number of elements in the HashSet.
  5. Collection Operations:
    • addAll(Collection<? extends E> collection): Adds all elements from the specified collection to the HashSet.
    • retainAll(Collection<?> collection): Retains only the elements that are present in the specified collection.
    • containsAll(Collection<?> collection): Checks if the HashSet contains all the elements from the specified collection.
    • removeAll(Collection<?> collection): Removes all elements from the HashSet that are present in the specified collection.
  6. Conversions and Views:
    • toArray(): Converts the HashSet to an array.
    • iterator(): Provides an iterator to iterate through the elements of the HashSet.
  7. Comparison and Equality:
    • equals(Object object): Compares the HashSet with another object for equality.
    • hashCode(): Returns the hash code value for the HashSet.

These methods allow you to perform various operations on a HashSet in Java, such as adding, removing, checking for elements, managing the size and status, and performing set operations like union, intersection, and difference with other collections. HashSet provides efficient and convenient ways to manage a collection of unique elements in Java without any duplicates.

Example of Adding Elements in HashSet

import java.util.HashSet;

public class MyHashSetExample {
    public static void main(String[] args) {
        // Create a new HashSet to store integers
        HashSet<Integer> myNumberSet = new HashSet<>();

        // Adding elements to the HashSet using the add() method
        myNumberSet.add(5);
        myNumberSet.add(15);
        myNumberSet.add(25);
        myNumberSet.add(35);

        // Displaying the HashSet
        System.out.println("My HashSet: " + myNumberSet);
    }
}
Output:
My HashSet: [5, 35, 15, 25]

Explanation of this code:

  1. HashSet<Integer> myNumberSet = new HashSet<>(); :- This line creates a new HashSet called myNumberSet that will store integers. The HashSet is defined using generics, specifying that it will hold objects of type Integer.
  2. add(5); :- The add() method is used to add the integer value 5 to the HashSet myNumberSet.
  3. add(15); :- The add() method is used to add the integer value 15 to the HashSet myNumberSet.
  4. add(25); :- The add() method is used to add the integer value 25 to the HashSet myNumberSet.
  5. add(35); :- The add() method is used to add the integer value 35 to the HashSet myNumberSet.
  6. System.out.println(“My HashSet: ” + myNumberSet); :- This line prints the contents of the HashSet myNumberSet using the println() method. The output will display the elements of the HashSet in a random order, as HashSet does not maintain any specific order for its elements. For this specific example, the output might be: My HashSet: [5, 35, 15, 25]. However, the order may vary each time the program is executed.

Example of Accessing elements in a HashSet:

import java.util.HashSet;
import java.util.Iterator;

public class AccessHashSetExample {
    public static void main(String[] args) {
        // Create a new HashSet to store integers
        HashSet<Integer> numberSet = new HashSet<>();

        // Adding elements to the HashSet using the add() method
        numberSet.add(10);
        numberSet.add(20);
        numberSet.add(30);
        numberSet.add(40);

        // Accessing elements using an iterator
        Iterator<Integer> iterator = numberSet.iterator();
        while (iterator.hasNext()) {
            int number = iterator.next();
            System.out.println("Element: " + number);
        }

        // Accessing elements using a for-each loop
        for (int number : numberSet) {
            System.out.println("Element: " + number);
        }
    }
}
Output:
Element: 40
Element: 10
Element: 20
Element: 30
Element: 40
Element: 10
Element: 20
Element: 30

Explanation of this code:

  1. HashSet<Integer> numberSet = new HashSet<>(); :- This line creates a new HashSet named numberSet to store integers. The HashSet is defined using generics, specifying that it will hold objects of type Integer.
  2. add(10); :- The add() method is used to add the integer value 10 to the HashSet numberSet.
  3. add(20); :- The add() method is used to add the integer value 20 to the HashSet numberSet.
  4. add(30); :- The add() method is used to add the integer value 30 to the HashSet numberSet.
  5. add(40); :- The add() method is used to add the integer value 40 to the HashSet numberSet.
  6. Accessing elements using an iterator:
    • Iterator<Integer> iterator = numberSet.iterator(); :- We create an iterator to traverse through the elements in the numberSet
    • while (iterator.hasNext()) {: The hasNext() method checks if there is another element to be processed in the HashSet.
    • int number = iterator.next(); :- The next() method retrieves the next element from the HashSet, and it is stored in the variable number.
    • out.println(“Element: ” + number); :- The element number is then printed to the console within the while loop.
  7. Accessing elements using a for-each loop:
    • for (int number : numberSet) {: The for-each loop iterates through each element in the numberSet HashSet, and each element is stored in the variable number.
    • System.out.println(“Element: ” + number); :- The element number is then printed to the console within the for-each loop.

Example of Delete Specific element in a HashSet:

import java.util.HashSet;

public class RemoveHashSetExample {
    public static void main(String[] args) {
        // Create a new HashSet to store strings
        HashSet<String> myHashSet = new HashSet<>();

        // Adding elements to the HashSet using the add() method
        myHashSet.add("apple");
        myHashSet.add("banana");
        myHashSet.add("orange");

        // Displaying the initial HashSet
        System.out.println("Initial HashSet: " + myHashSet);

        // Removing an element from the HashSet using the remove() method
        myHashSet.remove("banana");

        // Displaying the updated HashSet
        System.out.println("Updated HashSet: " + myHashSet);
    }
}
Output:
Initial HashSet: [banana, orange, apple]
Updated HashSet: [orange, apple]

Explanation of this code:

  1. HashSet<String> myHashSet = new HashSet<>(); :- This line creates a new HashSet named myHashSet to store strings. The HashSet is defined using generics, specifying that it will hold objects of type String.
  2. add(“apple”); :- The add() method is used to add the string “apple” to the HashSet myHashSet.
  3. add(“banana”); :- The add() method is used to add the string “banana” to the HashSet myHashSet.
  4. add(“orange”); :- The add() method is used to add the string “orange” to the HashSet myHashSet.
  5. out.println(“Initial HashSet: ” + myHashSet); :- This line prints the contents of the HashSet myHashSet using the println() method. The output will display the initial elements of the HashSet, which may appear in a different order as HashSet does not maintain any specific order for its elements. For example, the output might be: Initial HashSet: [orange, banana, apple].
  6. remove(“banana”); :- The remove() method is used to remove the element “banana” from the HashSet myHashSet. After this line executes, the HashSet will no longer contain “banana”.
  7. System.out.println(“Updated HashSet: ” + myHashSet); :- This line prints the contents of the updated HashSet myHashSet after removing “banana”. The output will display the remaining elements in the HashSet, which may appear in a different order. For example, the output might be: Updated HashSet: [orange, apple].

Example ignoring duplicate elements in HashSet

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        // Create a new HashSet to store strings
        HashSet<String> wordSet = new HashSet<>();

        // Adding elements to the HashSet using the add() method
        wordSet.add("apple");
        wordSet.add("banana");
        wordSet.add("orange");
        wordSet.add("banana"); // This element is a duplicate and will be ignored

        // Displaying the HashSet
        System.out.println("HashSet: " + wordSet);
    }
}
Output:
HashSet: [orange, banana, apple]

Example of a HashSet with common methods and operations:

import java.util.HashSet;

public class HashSetExample {
    public static void main(String[] args) {
        // Create a new HashSet to store strings
        HashSet<String> wordSet = new HashSet<>();

        // Adding elements to the HashSet using the add() method
        wordSet.add("apple");
        wordSet.add("banana");
        wordSet.add("orange");

        // Displaying the HashSet
        System.out.println("HashSet: " + wordSet);

        // Checking existence of an element
        boolean containsApple = wordSet.contains("apple");
        System.out.println("Contains 'apple'? " + containsApple);

        // Size and status of the HashSet
        int setSize = wordSet.size();
        boolean isEmptySet = wordSet.isEmpty();
        System.out.println("Size of HashSet: " + setSize);
        System.out.println("Is HashSet empty? " + isEmptySet);

        // Removing an element
        wordSet.remove("banana");
        System.out.println("HashSet after removing 'banana': " + wordSet);

        // Iterating through the elements
        for (String word : wordSet) {
            System.out.println("Word: " + word);
        }

        // Clearing the HashSet
        wordSet.clear();
        System.out.println("HashSet after clearing: " + wordSet);
    }
}
Output:
HashSet: [banana, apple, orange]
Contains ‘apple’? true
Size of HashSet: 3
Is HashSet empty? false
HashSet after removing ‘banana’: [apple, orange]
Word: apple
Word: orange
HashSet after clearing: []

Explanation of this code:

In this example, we create a HashSet named wordSet and add three strings (“apple”, “banana”, and “orange”) to it. Then, we perform various common operations on the HashSet:

  1. Checking the existence of an element: We use the contains() method to check if the HashSet contains the string “apple”.
  2. Size and status of the HashSet: We use the size() method to get the number of elements in the HashSet, and the isEmpty() method to check if the HashSet is empty.
  3. Removing an element: We use the remove() method to remove the string “banana” from the HashSet.
  4. Iterating through the elements: We use a for-each loop to iterate through each element in the HashSet and print its value.
  5. Clearing the HashSet: We use the clear() method to remove all elements from the HashSet, making it empty.
Visited 1 times, 1 visit(s) today

Comments are closed.

Close