HashMap vs. HashSet in Java
The Java Collections Framework provides a versatile set of classes and interfaces for handling and manipulating collections of objects. Two commonly used classes in this framework are HashMap and HashSet, each serving a distinct purpose.
HashMap
HashMap is an implementation of the Map interface, designed to store key-value pairs. It offers a mechanism to associate keys with values, and the uniqueness of keys is a crucial aspect. Retrieval of values based on their associated keys is efficient in a HashMap. Below are its properties:
Internally, it uses a hash table to store key-value pairs. It calculates the hash code of the keys to determine the index where the values are stored.
It stores key-value pairs, where both the key and the value can be any Java object.
We can retrieve values based on keys. It provides methods like
get(key)to fetch the associated value.It allows a single null key and multiple null values.
We can iterate over key-value pairs using methods like
entrySet()orkeySet().It is useful when we need to associate a value with a unique key such as storing and retrieving data based on some identifier.
Coding example
Below is an example demonstrating the use of HashMap in Java.
import java.util.HashMap;import java.util.Map;class HashMapExample {public static void main(String[] args) {// HashMap ExampleMap<String, Integer> hashMap = new HashMap<>();hashMap.put("One", 1);hashMap.put("Two", 2);hashMap.put("Three", 3);System.out.println("Value associated with key 'Two': " + hashMap.get("Two"));// Iterate through the HashMapfor (Map.Entry<String, Integer> entry : hashMap.entrySet()) {System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());}}}
HashSet
In contrast to HashMap, HashSet belongs to the Set interface and focuses on storing a collection of unique elements. Under the hood, HashSet employs a HashMap to store its elements, utilizing the elements themselves as keys in the underlying HashMap. Below are its properties:
Internally, it is backed by a
HashMap. It stores elements as keys inHashMap, with a constant dummy value for all elements.It stores unique elements and only the elements (values) without any corresponding keys.
We can check for the presence of an element using methods like
contains(element).It allows a single null element.
We can iterate over elements using an iterator.
It is suitable for scenarios where we need to maintain a collection of unique elements, such as removing duplicates from a list.
Coding example
Below is an example demonstrating the use of HashSet in Java.
import java.util.HashSet;import java.util.Set;class HashSetExample {public static void main(String[] args) {// HashSet ExampleSet<String> hashSet = new HashSet<>();hashSet.add("Apple");hashSet.add("Orange");hashSet.add("Banana");System.out.println("Is 'Apple' present in the HashSet? " + hashSet.contains("Apple"));// Iterate through the HashSetfor (String element : hashSet) {System.out.println(element);}}}
HashMap vs. HashSet
The following table presents a comparison between HashMap and HashSet, highlighting their specific features and differences.
Feature | HashMap | HashSet |
Implementation | Uses a hash table to store key-value pairs | Uses a hash table to store unique elements |
Duplicates | Allows duplicate values but not duplicate keys | Does not allow duplicate elements |
Order | Does not maintain insertion order | Does not maintain insertion order |
Null values | Allows one null key and multiple null values | Allows one null element |
Performance | Slightly slower due to key-value mapping | Slightly faster for simple set operations |
Use cases | Storing key-value pairs with unique keys | Storing a collection of unique elements where element ordering is not important |
Uses
Below are the use cases of HashMap and HashSet.
HashMap
Data indexing: Use a
HashMapto index large datasets efficiently. For example, in a database application, we can useHashMapsto store the mapping of unique identifiers to corresponding records, enabling fast retrieval.Caching: Implement a caching mechanism using
HashMapto store frequently accessed data. This can be helpful in scenarios where we want to avoid expensive operations by storing and quickly retrieving previously computed results.Frequency counting: HashMaps are great for counting the frequency of elements in a collection. For instance, we can use a
HashMapto count the occurrences of each word in a text document by mapping words to their respective counts.
HashSet
Duplicate elimination: When dealing with a collection of elements where duplicates are not allowed,
HashSetcomes in handy. For example, maintaining a unique list of user preferences or tags in a system.Set operations: Perform set operations like union, intersection, and difference efficiently using
HashSet. This is useful in scenarios where we need to compare or combine unique sets of elements.Membership testing: Use
HashSetto check the membership of an element in constant time. This is beneficial in scenarios where we need to quickly determine whether an item exists in a large set, such as checking if a username is already taken in a user database.
Free Resources