Java – HashMap v/s HashSet

In this article, we will discuss difference between HashMap and HashSet classes in detail i.e.; HashMap v/s HashSet

1. HashMap v/s HashSet:

HashMap HashSet
HashMap implements Map interfaceHashSet implements Set interface
Used to store key-value pairs using put method

 

Example: hm.put(key, value);

Used to store only unique objects using add method

 

Example: hs.add(object);

HashMap doesn’t allow duplicate keys but values can be duplicated HashSet doesn’t allow duplicate objects
HashMap allows maximum of one null key but any number of NULL values allowedHashSet allows maximum of one null object to be added
HashMap internally uses an array of Entry<K,V> objectsHashSet internally uses HashMap to store unique objects
Performance-wise, HashMap is faster than HashSetPerformance-wise, HashSet is slower than HashMap

Q) When to use HashMap ?

  • HashMap stores key-value pairs which uses hashing technique to store key-value pairs where methods are NOT synchronized
  • So, search operation is faster with multiple threads access
  • So, if business requirement is to store key-value pairs for faster search operation or more number of search operation on the basis of keys; without concerning concurrent access of map
  • Then, HashMap is the very apt choice

Q) When to use HashSet ?

  • HashSet stores unique elements using hashing technique
  • So, search operation is faster
  • So, if business requirement is to store unique elements for faster search operation or more number of search operation without concerning insertion order
  • Then, HashSet is the very apt choice

Related Articles:

References:           

Happy Coding !!
Happy Learning !!

Java - Hashtable class with examples
Java - HashMap v/s LinkedHashMap v/s TreeMap