HashMap vs HashSet

Diehard04
2 min readJul 9, 2021

Hi, In this article we are going to discuss on HashMap and HashSet.

As both having advantages and disadvantages so in this article we will discuss the difference between them and their functionality and when to use which one.

Before going to discuss on difference between them let me give you some brief about them.

HashMap -Hashmap implement Map interface which maps key to value. It is not thread save neither synchronised mean it will not maintain order of insertion. Duplicate keys are not allowed in Hashmap but null key / value allowed.

HashMap<String, String> result = new HashMap<>();
/** adding each child node to HashMap key => value*/
result.put(JSON_ID, ID);
result.put(JSON_TT, No);

HasSet -HashSet implement set interface which doesn’t allowed duplicate value. In also not maintain order neither it is thread safe.

HashSet<String> setDate = new HashSet<>();
setDate.add("Date");
setDate.add("Time");

As we now pretty much understand what is Hashmap and Hashset so now we can discuss on 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.

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

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.

6. Performance : Hashmap is fater then Hashset as values are stored in keys

--

--

Diehard04

Full time Android Developer, FreeLancern, SpringBoot, Flutter Developer