Java HashSet Class

 The HashSet class of the Java Collections framework provides the functionalities of the hash table data structure.

Methods of HashSet

The HashSet class provides various methods that allow us to perform various operations on the set.

Insert Elements to HashSet

  • add() - inserts the specified element to the set
  • addAll() - inserts all the elements of the specified collection to the set

For example,

import java.util.HashSet;

class Main {
    public static void main(String[] args) {
        HashSet<Integer> evenNumber = new HashSet<>();

        // Using add() method
        evenNumber.add(2);
        evenNumber.add(4);
        evenNumber.add(6);
        System.out.println("HashSet: " + evenNumber);

        HashSet<Integer> numbers = new HashSet<>();
        
        // Using addAll() method
        numbers.addAll(evenNumber);
        numbers.add(5);
        System.out.println("New HashSet: " + numbers);
    }
}

Output:

HashSet: [2, 4, 6]
New HashSet: [2, 4, 5, 6]

Access HashSet Elements:

To access the elements of a hash set, we can use the iterator() method. In order to use this method, we must import the java.util.Iterator package. For example,

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

class Main {
    public static void main(String[] args) {
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(2);
        numbers.add(5);
        numbers.add(6);
        System.out.println("HashSet: " + numbers);

        // Calling iterator() method
        Iterator<Integer> iterate = numbers.iterator();
        System.out.print("HashSet using Iterator: ");
        // Accessing elements
        while(iterate.hasNext()) {
            System.out.print(iterate.next());
            System.out.print(", ");
        }
    }
}

Output:

HashSet: [2, 5, 6]
HashSet using Iterator: 2, 5, 6,

Remove Elements:

  • remove() - removes the specified element from the set
  • removeAll() - removes all the elements from the set

For example,

import java.util.HashSet;

class Main {
    public static void main(String[] args) {
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(2);
        numbers.add(5);
        numbers.add(6);
        System.out.println("HashSet: " + numbers);

        // Using remove() method
        boolean value1 = numbers.remove(5);
        System.out.println("Is 5 removed? " + value1);

        boolean value2 = numbers.removeAll(numbers);
        System.out.println("Are all elements removed? " + value2);
    }
}

Output:

HashSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? true

Other Methods Of HashSet

MethodDescription
clone()Creates a copy of the HashSet
contains()Searches the HashSet for the specified element and returns a boolean result
isEmpty()Checks if the HashSet is empty
size()Returns the size of the HashSet
clear()Removes all the elements from the HashSet