Difference between HashSet HashMap

Answer: Below are the differences:

HashSetHashMap
HashSet implements Set interface and it is backed by hash table (actually HashMap instance)HashMap is a Hash table based implementation of Map interface
HashSet store objectsHashMap store object as key and value pair
HashSet doesn’t allow duplicate element but null values are allowedHashMap does not allows duplicate key but null key and values are allowed
This interface doesn’t guarantee that order will remain constant over the timeOrdering of the element is not guaranteed over the time

Please have java class example below:

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;


public class HashSetMapTest {

    public static void main(String[] args) {
    
    HashMap<String, String> hashMap = 
        new HashMap<String, String>();
    hashMap.put("Java", "Java");
    hashMap.put("Honk", "Honk");
    hashMap.put("Test", "Test");
    hashMap.put("Test", "Test");
    hashMap.put(null,null);
    hashMap.put("abc",null);
    hashMap.put("def",null);
    System.out.println("HashMap example:\n");
    Set<Entry<String, String>> set = hashMap.entrySet();
    for (Entry<String, String> entry : set) {
        
        System.out.println("Key: "+entry.getKey()
            +" Value: "+entry.getValue());      
    }
    
    System.out.println("\nHashMap example:\n");
    
    HashSet<String> hashSet = new HashSet<String>();
    hashSet.add("Java Honk");
    hashSet.add("Java Honk");
    hashSet.add(null);
    hashSet.add(null);
    
    for (String string : hashSet) {
        System.out.println("Value: "+string);
        
    }
    
    }

}

Output:

Difference between HashSet HashMap

 

Leave a Reply

Your email address will not be published. Required fields are marked *