Difference between HashMap and HashSet in java

Let’s learn difference between hashmap and hashset in java.

Difference between HashMap and HashSet in java

HashSetHashMap
HashSet stores only objects.HashMap stores elements in key and value pairs. That is each element has its corresponding key which is used for retrieval during iteration.
Insertion order is not preserved. objects inserted are based on their hash code.Insertion order is not preserved.
Has add() method to add elements in hashset.Has put() method to add elements in hashmap.
Implementation of Set interface.Implementation of Map interface.
Do not allow duplicate elements.Does not allow duplicate keys.
HashSet allow only one null value.Allows one null key object and any number of null values.
HashSet is based on object. So retrieval of elements is slow.HashMap has unique key. Hence retrieval of elements is fast.
HashSet internally uses hashmap for implementation.HashMap do not implement hashset or any other set internally.

Java HashMap example

import java.util.HashMap;
public class HashMapExample
{
   public static void main(String[] args)
   {
      HashMap<Integer, String> hm = new HashMap<Integer, String>();
      // add elements
      hm.put(10,"Apple");
      hm.put(20,"Banana");
      hm.put(30,"Cherry");
      hm.put(40,"Dragonfruit");
      // print HashMap elements
      System.out.println("HashMap elements: " + hm);
      // storing data with duplicate key
      hm.put(20, "Banana");
      System.out.println("After inserting duplicate key: " + hm);
   }
}

Output:

HashMap elements: {20=Banana, 40=Dragonfruit, 10=Apple, 30=Cherry}
After inserting duplicate key: {20=Banana, 40=Dragonfruit, 10=Apple, 30=Cherry}


Java HashSet example

import java.util.HashSet;
public class HashSetExample 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>(); 
      hs.add("Banana");    
      hs.add("Orange");    
      hs.add("Apple");   
      hs.add("Pineapple");  
      hs.add("Mango");
      System.out.println("Before adding duplicate values: " + hs);
      // adding duplicate elements 
      hs.add("Banana"); 
      hs.add("Orange");
      System.out.println("After adding duplicate values: " + hs);
      // adding null values
      hs.add(null); 
      hs.add(null);
      // printing HashSet elements 
      System.out.println("After adding null values: " + hs);
   }
}

Output:

Before adding duplicate values: [Apple, Mango, Pineapple, Orange, Banana]
After adding duplicate values: [Apple, Mango, Pineapple, Orange, Banana]
After adding null values: [null, Apple, Mango, Pineapple, Orange, Banana]


Also read – encapsulation in java