Difference between HashMap and HashSet

Last Updated : 18 Mar, 2026

HashMap and HashSet are part of the Java Collection Framework used for efficient data storage and retrieval. They differ mainly in how data is stored and how uniqueness is maintained.

  • HashMap stores data in key-value pairs
  • HashSet stores only unique elements
  • Both use hashing for fast operations

HashMap

HashMap is a data structure that stores elements in key-value pairs, where each key is unique and maps to a value. It is widely used when we need to associate one value with another.

  • Allows one null key and multiple null values
  • Uses put() method to insert elements
Java
import java.util.*;

public class Geeks{
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Java");
        map.put(2, "Python");
        map.put(1, "C++"); // replaces previous value
        System.out.println(map);
    }
}

Output
{1=C++, 2=Python}

HashSet

HashSet is a collection that stores only unique elements and does not allow duplicates. It is useful when we only care about distinct values.

  • Allows only one null value
  • Uses add() method to insert elements
Java
import java.util.*;

public class Geeks{
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("Java");
        set.add("Python");
        set.add("Java"); // duplicate ignored
        System.out.println(set);
    }
}

Output
[Java, Python]

HashMap vs HashSet

HashMapHashSet
Stores key-value pairsStores only unique elements
Keys are unique, values can repeatNo duplicate elements allowed
Allows one null key and multiple null valuesAllows only one null value
Uses put() methodUses add() method
Implements Map interfaceImplements Set interface
Used for mapping dataUsed for storing unique values
Comment