HashMap vs HashSet in Java with Examples
#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.
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));
}
}
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);
}
}
Feature | HashMap | HashSet |
---|---|---|
Data Structure | Stores key-value pairs (Map) | Stores unique values (Set) |
Duplicates | Keys unique, values can be duplicated | No duplicate elements allowed |
Access | Access using keys | Access using iteration only |
Nulls Allowed | One null key, multiple null values | One null element only |
Performance | O(1) average for operations | O(1) average for operations |
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.
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.