A HashMap in Java is a part of the Java Collections Framework and is implemented in the java.util package. It is a map-based collection that stores key-value pairs, where each key is associated with exactly one value. The key in a HashMap must be unique, but values can be duplicated. It provides fast lookups and is commonly used for efficient data storage and retrieval.
Characteristics of HashMap
1. No Duplicate Keys: Each key is unique; if you try to insert a new entry with a key that already exists, the old value will be replaced with the new one.
2. Unordered: HashMap does not guarantee any specific order of the entries.
3. Allows Nulls: It allows one null key and any number of null values.
4. Performance: Operations like get(), put(), and remove() are performed in constant time O(1) on average, but the performance may degrade in some rare cases when hash collisions occur.
Import the HashMap Class
You need to import the HashMap class from the java.util package.
import java.util.HashMap; // Import HashMap from java.util package
Create a HashMap
To create a HashMap, specify the types for the key and value. For example, if the keys are strings and the values are integers, you would declare it like this:
// Creating a HashMap with String keys and Integer values
HashMap map = new HashMap<>();
Adding Key-Value Pairs to the HashMap
Use the put() method to add entries to the HashMap. The first parameter is the key, and the second is the value.
map.put("John", 35); // John is the key, 35 is the value
map.put("Tom", 30); // Tom is the key, 30 is the value
map.put("Mark", 25); // Mark is the key, 25 is the value
Accessing Values Using Keys
You can retrieve values from the HashMap using the get() method by providing the key. If the key exists, it returns the associated value; otherwise, it returns null.
// Accessing values using keys
System.out.println("John's Age: " + map.get("John")); // Output: John's Age: 35
System.out.println("Tom's Age: " + map.get("Tom")); // Output: Tom's Age: 30
System.out.println("Mark's Age: " + map.get("Mark")); // Output: Tom's Age: 25
Checking if a Key or Value Exists
You can check if a specific key or value exists using the containsKey() and containsValue() methods:
System.out.println("Contains key 'John': " + map.containsKey("John")); // Output: true
System.out.println("Contains value 25: " + map.containsValue(25)); // Output: true
System.out.println("Contains key 'Alan': " + map.containsKey("Alan")); // Output: false
Removing Entries from the HashMap
You can remove an entry using the remove() method by specifying the key.
map.remove("Mark"); // Removes the entry for Mark
System.out.println("Map after removing Mark: " + map);
Checking the Size of the HashMap
You can check how many entries are currently stored in the HashMap using the size() method.
System.out.println("Size of the map: " + map.size()); // Output: 2
Iterating Over the HashMap
You can iterate over the entries in the HashMap using an enhanced for loop or using an iterator.
// Iterating over the key-value pairs using for-each loop
for (HashMap.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
Output:
Tom: 30
Clearing All Entries
You can remove all entries from the HashMap using the clear() method.
map.clear();
System.out.println("Map after clearing: " + map); // Output: {}
Complete Example of Using HashMap
import java.util.HashMap; // Import HashMap from java.util package
public class Main {
public static void main(String[] args) {
// Step 1: Create a HashMap
HashMap map = new HashMap<>();
// Step 2: Add key-value pairs to the HashMap
map.put("John", 25);
map.put("Tom", 30);
map.put("Mark", 25);
// Step 3: Accessing values using keys
System.out.println("John's Age: " + map.get("John")); // Output: John's Age: 25
System.out.println("Tom's Age: " + map.get("Tom")); // Output: Tom's Age: 30
// Step 4: Check if key or value exists
System.out.println("Contains key 'John': " + map.containsKey("John")); // Output: true
System.out.println("Contains value 25: " + map.containsValue(25)); // Output: true
System.out.println("Contains key 'Alan': " + map.containsKey("Alan")); // Output: false
// Step 5: Remove an entry from the HashMap
map.remove("Mark"); // Removes the entry for Mark
System.out.println("Map after removing Mark: " + map); // Output: {John=35, Tom=30}
// Step 6: Check the size of the HashMap
System.out.println("Size of the map: " + map.size()); // Output: 2
// Step 7: Iterate over the HashMap entries
for (HashMap.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Step 8: Clear all entries from the HashMap
map.clear();
System.out.println("Map after clearing: " + map); // Output: {}
}
}
Output:
Tom’s Age: 30
Contains key ‘John’: true
Contains value 25: true
Contains key ‘Alan’: false
Map after removing Mark: {Tom=30, John=25}
Size of the map: 2
Tom: 30
John: 25
Map after clearing: {}