-
Hajipur, Bihar, 844101
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.
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.
No Duplicates: HashSet automatically removes duplicate elements.
Unordered: Elements are not stored in the order of insertion.
Allows null: HashSet allows one null element.
Fast Operations: Average time complexity for add, remove, and search operations is O(1).
Non-Synchronized: It’s not thread-safe, meaning multiple threads can modify it simultaneously without synchronization.
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.
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.
for (String fruit : fruits) {
System.out.println(fruit);
}
Iterator<String> itr = fruits.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
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();
You can check whether a particular element exists in the set using:
fruits.contains("Apple"); // returns true
fruits.contains("Grapes"); // returns false
To find the number of elements present:
System.out.println("Total elements: " + fruits.size());
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.
| 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 |
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.
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.
| 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 |
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.
Write a Java program to create a HashSet of colors and print all the elements using a for-each loop.
Create a program to add elements to a HashSet, then try to add duplicates and observe the result.
Write a Java program to check whether a specific element exists in a HashSet.
Create a program that removes an element from a HashSet and displays the updated set.
Write a Java program to find the size of a HashSet and clear all elements.
Create a program that converts a HashSet into an ArrayList.
Write a Java program to iterate through a HashSet using an Iterator.
Create a program that compares two HashSets and finds common elements.
Write a Java program to create a HashSet of integers and find the maximum and minimum values.
Create a program to copy all elements from one HashSet to another HashSet.