HashMap vs HashSet in Java

We are going to discuss the differences between HashSet vs HashMap in this article. These are two of the most important Collection classes in Java. They are present in the java.util package. We use both of them for serving various purposes of data structures.

This topic is really important and this question is frequently asked in many interviews. Hence, you must thoroughly know about them and the differences between them. Before discussing the differences, we will first look at their introduction and discuss them separately.

HashMap vs HashSet

What is a HashSet in Java?

HashSet is a collection framework that implements the Set interface and does not allow any duplicate values. All the objects stored in the HashSet must override the equals() and hashCode() methods so that we can check for duplicate values.

The HashSet is not thread safe and is not synchronized. There is a method add() which adds elements in a HashSet.

The syntax of this method is:

public boolean add(Object obj)

This method returns a boolean value. It returns true if the element is unique and adds the element successfully, and returns false if there is a duplicate value added to the HashSet.

For example:

HashSet vehicleSet = new HashSet();
vehicleSet.add(“Car”);
vehicleSet.add(“Motorcycle”);
vehicleSet.add(“Bus”);

What is a HashMap in Java?

A HashMap is a Hash table that implements the Map interface and maps a key to value. HashMap also does not allow duplicate keys but allows duplicate values in it. The map interface has two implementation classes which are Treemap and the HashMap.

The difference between both is that the TreeMap maintains the order of objects but the HashMap does not maintain the order of objects. The HashMap is not thread-safe and is not synchronized. It does not allow duplicate values but it allows the null values.

To add the elements in a Hashmap, the put() method which accepts a key and a value.

Its syntax is:

public Object put(Object key, Object value)

For example:

HashMap<Integer, String> vehicleHashMap = new HashMap<Integer, String>();
vehicleHashMAp.put( 1, “Car” );
vehicleHashMAp.put( 2, “Motorcycle” );
vehicleHashMAp.put( 3, “Bus” );

So, this was a brief introduction to both HashSet and HashMap. We came to know that both are not thread-safe and synchronized.

Now, let’s discuss the differences between them.

Java HashSet Vs HashMap

We will discuss each difference with a specific parameter:

1. Implementation Hierarchy

The HashSet implements the Set interface of Java while the HashMap implements the Map interface. The Set interface extends the Collection interface which is the top-level interface of the Java Collection framework, while the Map interface does not extend any interface.

HashSet in java

HashMap in java

2. Data Storage

The HashSet stores the data in the form of objects, while the HashMap stores the data in the form of key-value pairs. In HashMap, we can retrieve each value using the key.

For example:

HashSet<String> hs = new HashSet<String>();
hs.add(“Java”);

HashMap<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1, “Java”);

3. Duplicate Values

HashSet does not allow you to add duplicate values. But HasMap stores the key-value pairs and allows the duplicate keys but not duplicate values. If we add the duplicate key, then it uses the new value with that key.

4. Null Values

HashSet allows a single null value; after adding a null value, HashSet does not allow to add more null values. On the other hand, HashMap allows multiple null values but a single null key.

5. Internal Implementation

HashSet internally implements the HashMap, while HasMap does neither implement a HashSet or any Set.

6. Methods to Insert Elements

There are predefined methods for both HashSet and HashMap to store or add elements. The add() method adds elements in a HashSet while the put() method adds or stores elements in a HashMap. While using the add method, we directly pass the value in the form of an object.

But when using the put() method, we need to pass the key as well as the value to add the element in a HashSet.

7. Mechanism to Add Elements

HashMap internally uses a hashing method to store the elements. On the other hand, the HashSet uses the HashMap object to store or add the elements.

8. Performance

The speed of HashSet is slower than that of HashMap. The reason that HashMap is faster than HashSet is that the HashMap uses the unique keys to access the values. It stores each value with a corresponding key and we can retrieve these values faster using keys during iteration.

While HashSet is completely based on objects and therefore retrieval of values is slower.

9. Dummy Values

As we know that HashSet uses the HashMap to add elements. In HashSet, we pass the elements in the add(Object) method, and the argument passed in this method acts as a key. Java internally uses dummy values for each value passed in the add method.

10. Example

Let’s see the examples of HashSet and HashMap.

  • HashSet- {1,2,3,4} or {“Java”, “C++”, “Python”}
  • HashMap- {a->1, b->2, c->3,d->4} or{1->”Java”, 2->”Python”, 3->“C++”}

HashSet vs HashMap in Java in Tabular Form

After discussing the differences, we will compare them in the tabular form. The differences are given below:

Parameter HashSet HashMap
Implementation Implements Set interface Implements Map Interface
Stores Objects Key-Value pairs
Duplicate values HashSet does not allow duplicate values. HashMap allows duplicate keys but does not allow duplicate values.
Null Values Single Null value allowed A single null key but multiple null values are allowed.
Method to insert elements We use the add() method that inserts the  elements in the HashSet. We use the put() method to insert elements in the HashMap.
Number of objects We can create only one object  during the addition of elements. We create two objects during addition of objects.
Performance Slower Faster
Uses The use of HashSet is to maintain the uniqueness of data The use of hashMap is when the uniqueness of data is not much important. 

Examples to understand Difference Between HashSet and HashMap in Java

Now, we will understand HashSet and HashMap with the help of Java programs:

Code to understand Java HashSet:

package com.techvidvan.hahssetvshashmap;
import java.util.HashSet;
public class HashSetDemo {
  public static void main(String[] args) {
    // Create a HashSet
    HashSet < String > hset = new HashSet < String > ();

    //add elements to HashSet using add() method
    hset.add("Java");
    hset.add("Python");
    hset.add("Ruby");
    hset.add("C++");

    // Displaying HashSet elements
    System.out.println("HashSet contains:\n" + hset);
    //Adding duplicate values
    hset.add("Java");
    hset.add("Ruby");
    System.out.println("After adding duplicate values, HashSet contains:\n" + hset);
    //Adding null values to HashSet
    hset.add(null);
    System.out.println("After adding null values for the first time, HashSet contains:\n" + hset);
    hset.add(null);
    System.out.println("After adding null values for the second time, HashSet contains:\n" + hset);
  }
}

Output

HashSet contains:
[Java, C++, Ruby, Python]
After adding duplicate values, HashSet contains:
[Java, C++, Ruby, Python]
After adding null values for the first time, HashSet contains:
[null, Java, C++, Ruby, Python]
After adding null values for the second time, HashSet contains:
[null, Java, C++, Ruby, Python]

Code to understand Java HashMap:

package com.techvidvan.hahssetvshashmap;
import java.util.HashMap;
public class HashMapDemo {
  public static void main(String[] args) {
    // Creating a HashMap
    HashMap < Integer,
    String > hmap = new HashMap < Integer,
    String > ();

    //add elements to HashMap using put() method
    hmap.put(1, "Java");
    hmap.put(2, "Python");
    hmap.put(3, "Ruby");
    hmap.put(4, "C++");

    // Displaying HashMap elements
    System.out.println("HashMap contains:\n" + hmap);

    //Adding duplicate values to a HashMap
    hmap.put(4, "JavaScript");
    System.out.println("After adding duplicate values, HashSet contains:\n" + hmap);
  }
}

Output

HashMap contains:
{1=Java, 2=Python, 3=Ruby, 4=C++}
After adding duplicate values, HashSet contains:
{1=Java, 2=Python, 3=Ruby, 4=JavaScript}

When to use HashSet and HashMap in Java?

We should prefer to use HashSet rather than Hashmap when we want to maintain the uniqueness in the Collection object. In all other cases, we should use HashMap over HashSet as its performance is better than HashSet.

Conclusion

In this article, we discussed every difference between HashSet and HashMap. We use both of them as a Collection class in Java. HashSet implements Set interface and works internally like HashMap, while HashMap implements the Map interface.

The HashMap should be always preferred to use unless there is a need to maintain the uniqueness of elements in the Collection.

Hope Hashset vs Hashmap is clear to you. Do share your feedback in the comment section.

TechVidvan Team

The TechVidvan Team delivers practical, beginner-friendly tutorials on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our experts are here to help you upskill and excel in today’s tech industry.