Java HashSet Tutorial

A HashSet is a part of the Java Collections Framework and implements the Set interface. It is used to store unique elements (no duplicates) and allows null values.

It does not maintain any particular order of the elements. HashSet is backed by a HashMap, and it uses hashing to store elements, offering constant time performance (on average) for the basic operations: add, remove, contains, and size.

In this tutorial, we'll cover the most common operations with HashSet along with several code examples to help you understand how it works.

1. Creating a HashSet

To create a HashSet, you simply declare it with the type of elements it will hold, and you can optionally initialize it with some capacity.

Example:

import java.util.HashSet;

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

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

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

Explanation:

We declare a HashSet to store String objects.
add() method is used to insert elements into the set.

Output:
HashSet: [Apple, Banana, Orange].

2. Adding Elements to a HashSet

You can add elements to the HashSet using the add() method. If you try to add a duplicate element, the set will ignore it since HashSet does not allow duplicates.

Example:

import java.util.HashSet;

public class AddElements {
    public static void main(String[] args) {
        HashSet numbers = new HashSet<>();

        // Adding elements to the HashSet
        numbers.add(10);
        numbers.add(20);
        numbers.add(30);

        // Trying to add a duplicate element
        boolean added = numbers.add(20); // Will return false

        System.out.println("HashSet: " + numbers);
        System.out.println("Was 20 added again? " + added);
    }
}

Explanation:

The add() method inserts elements into the set.
Trying to add a duplicate element (20) returns false, as sets do not allow duplicates.

Output:

HashSet: [10, 20, 30]
Was 20 added again? false

3. Checking if an Element Exists

You can check if an element is present in the HashSet using the contains() method. It returns true if the element exists and false otherwise.

Example:

import java.util.HashSet;

public class ContainsElement {
    public static void main(String[] args) {
        HashSet fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Check if "Banana" exists
        boolean hasBanana = fruits.contains("Banana");
        System.out.println("Does HashSet contain Banana? " + hasBanana);
    }
}

Explanation:

The contains() method checks if the element “Banana” is present in the HashSet.

Output:

Does HashSet contain Banana? true.

4. Removing Elements from a HashSet

You can remove elements from a HashSet using the remove() method. If the element exists, it will be removed and the method will return true; otherwise, it will return false.

Example:

import java.util.HashSet;

public class RemoveElement {
    public static void main(String[] args) {
        HashSet fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Removing "Banana" from the HashSet
        boolean removed = fruits.remove("Banana");
        System.out.println("Was Banana removed? " + removed);

        // Trying to remove an element that doesn't exist
        boolean removedMango = fruits.remove("Mango");
        System.out.println("Was Mango removed? " + removedMango);

        // Displaying the HashSet after removal
        System.out.println("HashSet: " + fruits);
    }
}

Explanation:

remove(“Banana”) removes the “Banana” element and returns true.
remove(“Mango”) attempts to remove an element that doesn't exist, and returns false.

Output:

Was Banana removed? true
Was Mango removed? false
HashSet: [Apple, Orange]

5. Iterating over a HashSet

You can iterate over a HashSet using enhanced for loops or the forEach() method with lambda expressions.

Using Enhanced For Loop:

import java.util.HashSet;

public class IterateHashSet {
    public static void main(String[] args) {
        HashSet fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Iterating over HashSet using enhanced for loop
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
    }
}

Using forEach() Method with Lambda Expression:

import java.util.HashSet;

public class IterateWithLambda {
    public static void main(String[] args) {
        HashSet fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Iterating over HashSet using forEach and lambda expression
        fruits.forEach(fruit -> System.out.println(fruit));
    }
}

Explanation:

Both examples iterate over each element in the HashSet and print them.
Since HashSet does not guarantee any particular order, the output may vary.

6. Checking the Size of a HashSet

You can check how many elements are present in a HashSet using the size() method.

Example:

import java.util.HashSet;

public class HashSetSize {
    public static void main(String[] args) {
        HashSet fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

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

Explanation:

size() returns the number of elements in the HashSet.

Output:

Size of HashSet: 3.

7. Clearing All Elements in a HashSet

You can remove all elements from a HashSet using the clear() method.

Example:

import java.util.HashSet;

public class ClearHashSet {
    public static void main(String[] args) {
        HashSet fruits = new HashSet<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Clearing all elements from the HashSet
        fruits.clear();

        // Checking if the HashSet is empty
        boolean isEmpty = fruits.isEmpty();
        System.out.println("Is HashSet empty? " + isEmpty);
    }
}

Explanation:

clear() removes all elements from the HashSet.
isEmpty() checks if the set is empty after clearing it.

Output:

Is HashSet empty? true.

8. Combining Two HashSets (Union)

You can combine two HashSet objects by using the addAll() method, which adds all elements from one set to another.

Example:

import java.util.HashSet;

public class CombineHashSets {
    public static void main(String[] args) {
        HashSet set1 = new HashSet<>();
        set1.add("Apple");
        set1.add("Banana");

        HashSet set2 = new HashSet<>();
        set2.add("Orange");
        set2.add("Apple"); // Duplicate element

        // Union of set1 and set2
        set1.addAll(set2);

        // Displaying the combined HashSet
        System.out.println("Combined HashSet: " + set1);
    }
}

Explanation:

addAll() combines two sets by adding all elements from set2 to set1. Duplicate elements (like “Apple”) are ignored.

Output:

Combined HashSet: [Apple, Banana, Orange].

9. Finding Common Elements (Intersection)

You can find the common elements between two HashSet objects by using the retainAll() method.

Example:

import java.util.HashSet;

public class IntersectionHashSets {
    public static void main(String[] args) {
        HashSet set1 = new HashSet<>();
        set1.add("Apple");
        set1.add("Banana");
        set1.add("Cherry");

        HashSet set2 = new HashSet<>();
        set2.add("Banana");
        set2.add("Cherry");
        set2.add("Orange");

        // Intersection of set1 and set2
        set1.retainAll(set2);

        // Displaying the common elements
        System.out.println("Common elements: " + set1);
    }
}

Explanation:

retainAll() keeps only the elements that are common between set1 and set2.

Output:

Common elements: [Banana, Cherry].

10. Removing Common Elements (Difference)

You can remove the common elements between two HashSet objects using the removeAll() method.

Example:

import java.util.HashSet;

public class DifferenceHashSets {
    public static void main(String[] args) {
        HashSet set1 = new HashSet<>();
        set1.add("Apple");
        set1.add("Banana");
        set1.add("Cherry");

        HashSet set2 = new HashSet<>();
        set2.add("Banana");
        set2.add("Cherry");
        set2.add("Orange");

        // Difference between set1 and set2
        set1.removeAll(set2);

        // Displaying the result
        System.out.println("Elements in set1 after removing common elements: " + set1);
    }
}

Explanation:

removeAll() removes all elements that are common between set1 and set2.

Output:

Elements in set1 after removing common elements: [Apple].

11. HashSet with Custom Objects

You can use custom objects in a HashSet, but you need to override the equals() and hashCode() methods to ensure correct behavior.

Example:

import java.util.HashSet;
import java.util.Objects;

class Employee {
    String name;
    int id;

    public Employee(String name, int id) {
        this.name = name;
        this.id = id;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Employee employee = (Employee) o;
        return id == employee.id && Objects.equals(name, employee.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, id);
    }
}

public class HashSetCustomObject {
    public static void main(String[] args) {
        HashSet employees = new HashSet<>();

        employees.add(new Employee("John", 101));
        employees.add(new Employee("Alice", 102));
        employees.add(new Employee("John", 101)); // Duplicate based on equals() and hashCode()

        // Displaying the HashSet
        employees.forEach(emp -> System.out.println(emp.name + " - " + emp.id));
    }
}

Explanation:

We override equals() and hashCode() to ensure that objects are compared correctly in the HashSet.

Output:

John - 101
Alice - 102

Conclusion

The HashSet class is a powerful tool when you need to store unique elements in an unordered collection.

It is very efficient in terms of performance due to its constant-time complexity for common operations like add, remove, and contains.

Using HashSet is especially useful when you need to avoid duplicate entries in your collection.

Related posts

Java Interrupting a Thread Tutorial with Examples

Reentrant Monitors in Java tutorial with code examples

Joining Threads in Java tutorial with code examples