Java HashSet


In Java, a HashSet is one of the most commonly used data structures from the Collection Framework. It is used to store unique elements without any specific order. If you ever need to keep a collection of items where duplicates are not allowed, HashSet is the best choice. It works on the principle of hashing, similar to a HashMap, but it only stores values, not key-value pairs.

What is HashSet in Java?

A HashSet is a collection that contains no duplicate elements. It implements the Set interface and is backed by a HashMap internally. Each element you add to a HashSet is stored as a key in an internal HashMap, with a dummy value.

The HashSet does not maintain any order of elements — it may display data in a different sequence than you inserted it. Its main advantages are fast performance, no duplicates, and efficient searching.

Syntax:

HashSet<Type> setName = new HashSet<>();

Example:

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

This creates an empty HashSet that can store strings.

Features of HashSet

  1. No Duplicates: HashSet automatically removes duplicate elements.

  2. Unordered: Elements are not stored in the order of insertion.

  3. Allows null: HashSet allows one null element.

  4. Fast Operations: Average time complexity for add, remove, and search operations is O(1).

  5. Non-Synchronized: It’s not thread-safe, meaning multiple threads can modify it simultaneously without synchronization.

Creating and Adding Elements to a HashSet

Here’s how you can create a HashSet and add elements:

import java.util.*;

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

        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");
        fruits.add("Banana"); // duplicate value

        System.out.println(fruits);
    }
}

Output:

[Apple, Banana, Mango]

Even though "Banana" was added twice, the HashSet keeps only one copy because duplicates are not allowed.

Accessing Elements from a HashSet

You cannot access elements by index because HashSet does not maintain order.
However, you can use a for-each loop or an iterator to traverse through its elements.

Example using for-each loop:

for (String fruit : fruits) {
    System.out.println(fruit);
}

Example using Iterator:

Iterator<String> itr = fruits.iterator();
while (itr.hasNext()) {
    System.out.println(itr.next());
}

Removing Elements from a HashSet

To remove elements, use the remove() or clear() method.

fruits.remove("Banana");
System.out.println(fruits);

Output:

[Apple, Mango]

If you want to remove all elements:

fruits.clear();

Checking for Existence

You can check whether a particular element exists in the set using:

fruits.contains("Apple"); // returns true
fruits.contains("Grapes"); // returns false

Size of a HashSet

To find the number of elements present:

System.out.println("Total elements: " + fruits.size());

Example: Removing Duplicates from a List

A practical use of HashSet is removing duplicates from a list.

import java.util.*;

public class RemoveDuplicates {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Anita", "Riya", "Anita", "Kavya", "Riya");

        HashSet<String> uniqueNames = new HashSet<>(names);

        System.out.println("Unique Names: " + uniqueNames);
    }
}

Output:

Unique Names: [Anita, Riya, Kavya]

Here, HashSet automatically removes all duplicate names.

Important Methods in HashSet

Method Description
add(element) Adds an element to the set
remove(element) Removes the specified element
clear() Removes all elements from the set
contains(element) Checks if the element exists
size() Returns the number of elements
isEmpty() Checks if the set is empty
iterator() Returns an iterator for traversal

Example: HashSet with Integers

import java.util.*;

public class IntegerSetExample {
    public static void main(String[] args) {
        HashSet<Integer> numbers = new HashSet<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(10);
        numbers.add(30);

        System.out.println("Numbers: " + numbers);
    }
}

Output:

Numbers: [20, 10, 30]

Even though “10” was added twice, it appears only once in the output.

HashSet with Objects

You can also store user-defined objects inside a HashSet.
However, for it to detect duplicates correctly, you must override equals() and hashCode() methods in your class.

import java.util.*;

class Student {
    int id;
    String name;

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

    public int hashCode() {
        return id;
    }

    public boolean equals(Object obj) {
        Student s = (Student) obj;
        return this.id == s.id;
    }
}

public class ObjectHashSet {
    public static void main(String[] args) {
        HashSet<Student> set = new HashSet<>();
        set.add(new Student(1, "Anita"));
        set.add(new Student(2, "Meera"));
        set.add(new Student(1, "Anita")); // duplicate ID

        System.out.println("Total Students: " + set.size());
    }
}

Output:

Total Students: 2

The duplicate student is ignored because of the overridden equals() and hashCode() methods.

Difference Between HashSet and TreeSet

Feature HashSet TreeSet
Order Unordered Sorted in ascending order
Performance Faster (O(1)) Slower (O(log n))
Null Elements Allows one null Does not allow null
Backed By HashMap TreeMap

Summary of the Tutorial

A HashSet in Java is a powerful tool to store unique elements efficiently. It’s ideal for removing duplicates, performing membership checks, or managing unique data collections. Since it uses hashing, it provides excellent performance for add, remove, and search operations. Understanding HashSet helps you handle uniqueness and improve performance in applications dealing with large datasets.


Practice Questions

  1. Write a Java program to create a HashSet of colors and print all the elements using a for-each loop.

  2. Create a program to add elements to a HashSet, then try to add duplicates and observe the result.

  3. Write a Java program to check whether a specific element exists in a HashSet.

  4. Create a program that removes an element from a HashSet and displays the updated set.

  5. Write a Java program to find the size of a HashSet and clear all elements.

  6. Create a program that converts a HashSet into an ArrayList.

  7. Write a Java program to iterate through a HashSet using an Iterator.

  8. Create a program that compares two HashSets and finds common elements.

  9. Write a Java program to create a HashSet of integers and find the maximum and minimum values.

  10. Create a program to copy all elements from one HashSet to another HashSet.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top