HashSet vs HashMap in Java

Free Java courses with 37 real-time projects - Learn Java

The java collection framework was introduced to help programmers store and manipulate data at an ease. These Collection Framework classes and interfaces are part of the java.util package. The HashSet and HashMap are part of this collection framework and serve various purposes in data handling. In this article, we will do a comparative study of these two classes and decide which class to use and for which scenario.

HashSet in Java:

HashSet is a class that is part of the collection framework and implements the Set interface. The HashSet data structure does not allow duplicate values. Each HashSet has a distinct set of unique values. Each and every object in the HashSet must override the equals() and hashcode() methods to check for duplicate values.

The HashSet methods are not thread-safe and are not synchronized. To add a new value into the HashSet there is a method add() which adds the element into the HashSet.

Syntax of the add() method is:

public boolean add(Object obj)

This method returns true if the value is unique and is added successfully to the HashSet, else it returns false.

Code snippet to show the addition of new values to the HashSet:

HashSet DataFlair_Article = new HashSet();
DataFlair_Article.add(“Technical Content Writing”);
DataFlair_Article.add(“Java Tutorials”);
DataFlair_Article.add(“HashSet vs HashMap”);

HashMap in Java:

A HashMap class is also a part of the collection framework and implements the Map interface. It is useful while mapping a key to a value. HashMap does not allow duplicate keys, but duplicate values can be added to it.
The Hashmap does not maintain the order of insertion of the objects. The HashMap methods are not thread-safe as well and are also not synchronized. It allows null values in it.

To add an element into a HashMap, there is a method called the put() method, which takes key and value pairs as arguments and inserts them into the HashMap.

The Syntax of the put() method is:

public Object put(Object key, Object value)

It returns the object after inserting the value into it.

Code snippet to show the addition of new values to the HashMap:

HashMap<String, String> DataFlairIntern = new HashMap<String, String>();
DataFlairIntern.put( “Name: ”, “Arka” );
DataFlairIntern.put( “Role: ”, “Technical Content Writer” );
DataFlairIntern.put( “Topic”, “Java” );

Now that we have had a brief introduction to both the classes, let us dive into the differences between the two.

Java HashSet vs HashMap:

1. Hierarchy of implementation:

The HashSet class implements the Set interface whereas the HashMap class implements the Map interface. The Set interface then extends the Collection interface. The Collection and the Map interface are the top-level interfaces of the collection framework.

Let us understand this hierarchy with a simplified diagram.

hierarchy of implementation

2. Data Storage Format:

The HashSet stores data in the form of objects whereas the HashMap stores data in the form of Key-Value pair. We can retrieve the values from the HashMap using the keys.

Example:

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

HashMap<String, String> hm = new HashMap<String, String>();
hm.put(“Company: ”, “DataFlair”);

3. Duplicate Values:

HashSet does not allow any duplicate values in its data structure. The storage format of HashMap is a little different. It does not allow duplicate keys but it allows duplicate values. We can say that the key-value pair must be unique in the case of HashMap. If by any chance duplicate keys are added, it replaces the previous key value with the new one.

4. Null Values:

HashSet allows only one null value, no more null values can be added after that. On the other hand, HashMap allows multiple null values, but there can only exist only one null key.

5. Internal Implementation:

HashSet implements the HashMap class internally, whereas the HashMap neither implements the HashSet nor the Set interface internally.

6. Insertion of Elements:

Both HashSet and HashMap use predefined functions to add elements into the data structure. The HashSet uses the add() method, which takes an object as input and returns a boolean value. The HashMap uses the put() method, which takes a key-value pair as input and returns the object after adding the value.

Example:

HashSet DataFlair_Article = new HashSet();
DataFlair_Article.add(“Technical Content Writing”);
DataFlair_Article.add(“Java Tutorials”);
DataFlair_Article.add(“HashSet vs HashMap”);

HashMap<String, String> DataFlairIntern = new HashMap<String, String>();
DataFlairIntern.put( “Name: ”, “Arka” );
DataFlairIntern.put( “Role: ”, “Technical Content Writer” );
DataFlairIntern.put( “Topic: ”, “Java” );

7. Addition of elements internally:

The HashMap uses hashtable and hashing methods to store the elements internally. The HashSet on the other hand uses the HashMap objects internally to store the elements.

8. Performance:

HashSet works slower than HashMap. There are two reasons behind this, firstly HashMap stores data in form of key-value pair, which makes it easier to search data, corresponding to the objects stored in HashSet. Secondly, HashSet internally uses HashMap, thus making it slower than HashMap itself.

9. Dummy Values:

We know that the HashSet uses HashMap internally to add elements. The object passed through the add() method acts as the key value in the key-value pair of the HashMap. Java then uses a dummy value corresponding to the key value to complete the key-value pair.

10. Example:

This example shows how the values are stored in HashSet and HashMap.

HashSet: {“Technical Content Writer”,”Java Tutorials”,”HashSet vs HashMap”}
HashMap:{Name: ->Arka,Role: ->Technical Content Writer,Topic: ->Java}

Let us understand the difference between Java HashSet vs hashmap with a simple table:

ParameterHashSetHashMap
ImplementationIt implements the set interface.It implements the Map interface
StorageObjectsKey-Value pair
Duplicate valueNo duplicate values allowedAllows duplicate value but no duplicate keys.
Null ValueSingle Null value.Multiple null values, but only one null key.
The method used for insertionadd(object)put(key,value)
Number of objectsOnly one object can be added at a timeTwo objects can be added at a time.
PerformanceSlower Faster
UseTo maintain the uniqueness of data.To organize the data in key and value pairs.

Code to understand the Difference Between HashSet and HashMap in Java:

Code to understand Java HashSet:

package com.DataFlair.HashSetVSHashMap;
import java.util.HashSet;
public class HashSetClass
{
     public static void main(String[] args) 
     {
        HashSet < String > hashset = new HashSet < String > ();
        hashset.add("This");
        hashset.add("is");
        hashset.add("how");
        hashset.add("HashSet");
        hashset.add("Stores");
        hashset.add("Data");
        System.out.println("The HashSet contains:\n" + hashset);
        hashset.add("HashSet");
        hashset.add("Data");
        System.out.println("After trying to add duplicate values, The HashSet contains:\n" + hashset);
        hashset.add(null);
        System.out.println("After adding a null values for the first time, the HashSet contains:\n" + hashset);
        hashset.add(null);
        System.out.println("After trying to add a duplicate null value, the HashSet contains:\n" + hashset);
    }
}

The output of the above code is:

The HashSet contains:
[how, This, is, Data, Stores, HashSet]
After trying to add duplicate values, The HashSet contains:
[how, This, is, Data, Stores, HashSet]
After adding a null values for the first time, the HashSet contains:
[null, how, This, is, Data, Stores, HashSet]
After trying to add a duplicate null value, the HashSet contains:
[null, how, This, is, Data, Stores, HashSet]

We can see that the insertion order is not maintained in the HashSet. Also, duplicate values are not allowed.

Code to understand HashMap:

package com.DataFlair.HashSetVSHashMap;
import java.util.HashMap;
public class HashMapClass
{
    public static void main(String[] args) 
    {
        HashMap < Integer,String > hashmap = new HashMap < Integer,String > ();
        hashmap.put(1, "This");
        hashmap.put(2, "is");
        hashmap.put(3, "how");
        hashmap.put(4, "HashMap Stores Data");
        System.out.println("The HashMap contains:\n" + hashmap);
        hashmap.put(4, "HashMap Stores duplicate");
        System.out.println("After adding duplicate key values, the HashSet contains:\n" + hashmap);
  }
}

The output of the above code:

The HashMap contains:
{1=This, 2=is, 3=how, 4=HashMap Stores Data}
After adding duplicate key values, the HashSet contains:
{1=This, 2=is, 3=how, 4=HashMap Stores duplicate}

We can see that the insertion order is maintained, and the duplicate value replaces the old value.

When to use HashSet and HashMap in Java?

HashSet is only useful if and only if we need to maintain the uniqueness of data. In all other cases, HashMap is better, as it performs better than HashSet and also HashMap organizes data better than HashSet.

Conclusion:

So, we come to the end of our comparative study of HashSet and HashMap. In this article, we discussed both HashSet and HashMap and their differences. We also discuss in which scenario we should use HashSet and where to use HashMap. We can conclude that HashMap is better than HashSet in all circumstances, except for when we have to maintain the uniqueness of data.

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *