HashMap vs HashSet in Java with Examples

8/16/2025

#HashMap vs HashSet in Java with Examples

Go Back

HashMap vs HashSet in Java with Examples

Both HashMap and HashSet are part of the Java Collections Framework and are widely used for storing data. However, they serve different purposes and have unique characteristics. Let’s explore the differences with examples.


#HashMap vs HashSet in Java with Examples

HashMap in Java

  • Definition: A HashMap stores data in key-value pairs. Keys are unique, but values can be duplicated.

  • Common Implementations: HashMap, LinkedHashMap, TreeMap

  • Performance:

    • Insert, Delete, Search: O(1) on average

    • Iteration order: Unordered (unless using LinkedHashMap)

Example:

import java.util.*;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");

        System.out.println("HashMap: " + map);
        System.out.println("Value for key 2: " + map.get(2));
    }
}

HashSet in Java

  • Definition: A HashSet is a collection of unique elements without duplicates.

  • Common Implementations: HashSet, LinkedHashSet, TreeSet

  • Performance:

    • Insert, Delete, Search: O(1) on average

    • Iteration order: Unordered (unless using LinkedHashSet)

Example:

import java.util.*;

public class HashSetExample {
    public static void main(String[] args) {
        HashSet<String> set = new HashSet<>();
        set.add("Apple");
        set.add("Banana");
        set.add("Apple"); // Duplicate ignored

        System.out.println("HashSet: " + set);
    }
}

Key Differences Between HashMap and HashSet

FeatureHashMapHashSet
Data StructureStores key-value pairs (Map)Stores unique values (Set)
DuplicatesKeys unique, values can be duplicatedNo duplicate elements allowed
AccessAccess using keysAccess using iteration only
Nulls AllowedOne null key, multiple null valuesOne null element only
PerformanceO(1) average for operationsO(1) average for operations

When to Use What?

  • Use HashMap when you need to store key-value pairs.

  • Use HashSet when you need to store unique elements.

  • Use LinkedHashMap or LinkedHashSet when order matters.


Final Thoughts

Both HashMap and HashSet are optimized for performance, but they serve different purposes. HashMap is ideal for key-value lookups, while HashSet ensures uniqueness. Choosing the right one depends on your use case.

Table of content