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.does not maintain insertion order.
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