Java Collections – HashMap and HashSet

HashMap and HashSet are collections in Java which are most commonly used. Here we summarise key features:

HashMap   HashSet
Duplicates Yes, Duplicate values
but  no duplicate keys
No
Adding or Storing mechanism Hashing technique HashMap object
Dummy values No Yes
Implements Map Set
Number Of Objects required
during add operation
2 1

When to use HashMap and HashSet in Java ?

The only time we need to prefer HashSet over HashMap when we are asked to maintain uniqueness in our collection object. Otherwise , always prefer HashMap over HashSet as HashSet is just a wrapper around HashMap.

Difference between HashMap and HashSet 

1. Duplicates  :  HashSet does not allow duplicate values , in other words, adding a duplicate value leaves the HashSet object unchanged.

If the HashMap previously contain the mapping for the key, the old value is replaced. HashMap  does not allow duplicate keys. In other words, HashMap duplicate values can exist in HashMap.

2. Dummy value : There is no concept of dummy value in HashMap .

HashSet internally uses HashMap to add elements. In HashSet , the argument passed in add(Object) method serves as key K . we need to associate dummy value (automatically created by jdk) for each value  passed in add(Object) method.

3.  Implementation : HashMap implements Map interface, while HashSet implements Set interface.

4. Number of objects during add(put) operation :  HashMap requires two objects put(K key , V Value) to add an element to HashMap object.
HashSet requires only one object add(Object o) .

5.  Adding or Storing mechanism : HashMap internally uses hashing to add or store objects. HashSet internally uses HashMap object to add or store the objects.

 

Similarities between HashMap and HashSet

1. Performance : Performance of  add,put,remove operations are almost same i.econstant time for HashSet and HashMap. It is incorrect to say HashMap is faster than HashSet.

2. Insertion Order :  Both HashMap and HashSet does not guarantee that the order will remain constant over time.

3. Unsynchronized : Both HashMap and HashSet implementation is unsynchronized.

4. Iterator type  : Iterator’s returned by both (HashMap and HashSet) class’s iterator and collection view methods are fail-fast.

 

Example of HashMap and HashSet in Java

import java.util.HashMap;
import java.util.HashSet;

public class HashMapHashSetExample {
    
    public static void main(String[] args) { 
 
           
  
        HashSet<String> hashsetobj = new HashSet<String>();
        hashsetobj.add("Alive is awesome");
        hashsetobj.add("Love yourself");
        System.out.println("HashSet object output :"+ hashsetobj);
 
         
 
        HashMap hashmapobj = new HashMap();
        hashmapobj.put("Alive is ", "awesome");  
        hashmapobj.put("Love", "yourself"); 
        System.out.println("HashMap object output :"+hashmapobj);   
 
 }
}

 

admin has written 55 articles