HashMap v/s HashSet

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


HashMap v/s HashSet

HashMap  HashSet
HashMap implements Map interface HashSet 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 allowed HashSet allows maximum of one null object to be added
HashMap internally uses an array of Entry<K,V> objects HashSet internally uses HashMap to store unique objects
Performance-wise, HashMap is faster than HashSet Performance-wise, HashSet is slower than HashMap


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


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





Happy Coding !!
Happy Learning !!