Java HashSet
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Java HashSet

Jeevadharshan

Java HashSet  

The HashSet class is part of the Java Collections Framework and is used to store a collection of unique elements. It belongs to the java.util package and implements the Set interface. 
 
A HashSet ensures that duplicate elements are not stored. If you attempt to add the same element more than once, the duplicate entry will be ignored automatically. 
 
Unlike some other collection types, a HashSet does not maintain insertion order, meaning elements may appear in a different order than they were added. 
 
HashSet is widely used when you need fast lookup operations and unique data storage.  

Creating a HashSet in Java 

To use a HashSet, you must first import it from the java.util package, then create an object of the class. 
 
Example: Creating a HashSet 
 
import java.util.HashSet; 
 
public class CitySetExample { 
 
    public static void main(String[] args) { 
 
        HashSet<String> cities = new HashSet<>(); 
 
        cities.add("Chennai"); 
        cities.add("Delhi"); 
        cities.add("Mumbai"); 
        cities.add("Bangalore"); 
 
        System.out.println("Cities: " + cities); 
    } 
 
This program creates a HashSet that stores city names. Since HashSet stores unique values, duplicates are automatically ignored. 

Adding Elements to a HashSet 

You can insert elements into a HashSet using the add() method. 
 
Example: Adding Unique Product Names 
 
import java.util.HashSet; 
 
public class ProductSetExample { 
 
    public static void main(String[] args) { 
 
        HashSet<String> products = new HashSet<>(); 
 
        products.add("Laptop"); 
        products.add("Keyboard"); 
        products.add("Mouse"); 
        products.add("Laptop"); // Duplicate element 
 
        System.out.println("Available Products: " + products); 
    } 
 
Key Point 
 
Even though "Laptop" is added twice, it appears only once in the output because HashSet does not allow duplicate values. 

Checking if an Element Exists 

The contains() method checks whether a specific element exists in the HashSet. 
 
Example 
 
if(products.contains("Mouse")) { 
    System.out.println("Mouse is available in the set."); 
 
This method is very efficient and commonly used for fast membership checks. 

Removing Elements from a HashSet 

To remove an element from a HashSet, use the remove() method. 
 
Example 
 
products.remove("Keyboard"); 
 
If you want to remove all elements, use the clear() method. 
 
products.clear(); 

Finding the Size of a HashSet 

The size() method returns the total number of unique elements stored in the set. 
 
Example 
 
System.out.println("Total products: " + products.size()); 
 
Duplicate elements are not counted. 

Iterating Through a HashSet 

You can loop through the elements of a HashSet using a for-each loop. 
 
Example: Displaying Course Names 
 
import java.util.HashSet; 
 
public class CourseIteratorExample { 
 
    public static void main(String[] args) { 
 
        HashSet<String> courses = new HashSet<>(); 
 
        courses.add("Artificial Intelligence"); 
        courses.add("Machine Learning"); 
        courses.add("Cyber Security"); 
 
        for(String course : courses) { 
            System.out.println(course); 
        } 
    } 
 
Because HashSet does not maintain order, the elements may appear in any order during iteration. 
 
Example: Using a HashSet with Integers 
 
import java.util.HashSet; 
 
public class NumberSetExample { 
 
    public static void main(String[] args) { 
 
        HashSet<Integer> numbers = new HashSet<>(); 
 
        numbers.add(10); 
        numbers.add(25); 
        numbers.add(30); 
        numbers.add(10); // Duplicate 
 
        for(Integer num : numbers) { 
            System.out.println("Number: " + num); 
        } 
    } 

Using the var Keyword (Java 10+)  

Starting from Java 10, developers can use the var keyword to declare variables without explicitlywriting the type twice. 
 
The compiler automatically determines the type from the assigned value. 
 
Example 
 
var languages = new HashSet<String>(); 
 
languages.add("Java"); 
languages.add("Python"); 
languages.add("C++"); 
 
Although var makes code shorter, many developers still prefer using the explicit type declaration for better readability. 

Using the Set Interface with HashSet 

In Java, it is common practice to declare variables using the Set interface rather than the concrete class. 
 
Example 
 
import java.util.Set; 
import java.util.HashSet; 
 
public class ProgrammingLanguageSet { 
 
    public static void main(String[] args) { 
 
        Set<String> languages = new HashSet<>(); 
 
        languages.add("Java"); 
        languages.add("Python"); 
        languages.add("JavaScript"); 
 
        System.out.println(languages); 
    } 
 
This approach provides greater flexibility, allowing developers to change the implementation (for
example, switching from HashSet to another Set type) without modifying the rest of the code.
Our website uses cookies to enhance your experience. Learn More
Accept !