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
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
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
| HashMap | HashSet |
|---|---|
| Stores key-value pairs | Stores only unique elements |
| Keys are unique, values can repeat | No duplicate elements allowed |
| Allows one null key and multiple null values | Allows only one null value |
| Uses put() method | Uses add() method |
| Implements Map interface | Implements Set interface |
| Used for mapping data | Used for storing unique values |