HashMap is a part of the Java Collections Framework and is used to store key-value pairs. It implements the Map interface and uses a technique called hashing to store the elements.
HashMap provides fast access, insertion, and deletion (on average, O(1) time complexity).
In this tutorial, we will explore the most common operations that you can perform with a HashMap, along with code examples to help you understand how it works.
Table of Contents
Table of Contents
1. Creating a HashMap
You can create a HashMap to store elements of any data type for both key and value.
Example:
import java.util.HashMap; public class HashMapExample { public static void main(String[] args) { // Creating a HashMap of Integer keys and String values HashMap<Integer, String> map = new HashMap<>(); // Adding key-value pairs map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Cherry"); // Displaying the HashMap System.out.println("HashMap: " + map); } }
Explanation:
HashMap<Integer, String>: Integer is the key type, and String is the value type.
The put() method is used to insert key-value pairs.
Output: HashMap: {1=Apple, 2=Banana, 3=Cherry}.
2. Adding Elements to HashMap
To add elements to a HashMap, use the put() method. If the key already exists, the new value will replace the existing value.
Example:
public class AddElements { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); // Adding key-value pairs map.put("John", 25); map.put("Alice", 30); map.put("Bob", 22); // Printing the map System.out.println("HashMap: " + map); } }
Explanation:
Here, keys are String (names), and values are Integer (ages).
put() adds each key-value pair to the map.
Output: HashMap: {John=25, Alice=30, Bob=22}.
3. Accessing Elements in HashMap
To access elements, use the get() method, passing the key as an argument. If the key does not exist, it returns null.
Example:
public class AccessElements { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Cherry"); // Accessing value associated with key 2 String value = map.get(2); System.out.println("Value for key 2: " + value); } }
Explanation:
The get() method fetches the value associated with key 2.
Output: Value for key 2: Banana.
4. Removing Elements from HashMap
To remove an element from the HashMap, use the remove() method, passing the key of the element to be removed.
Example:
public class RemoveElements { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("John", 25); map.put("Alice", 30); map.put("Bob", 22); // Removing the entry with key "Alice" map.remove("Alice"); // Displaying the HashMap after removal System.out.println("HashMap after removal: " + map); } }
Explanation:
The remove() method deletes the entry with the key “Alice”.
Output: HashMap after removal: {John=25, Bob=22}.
5. Checking if a Key or Value Exists
You can use the containsKey() and containsValue() methods to check whether a key or value exists in the HashMap.
Example:
public class KeyValueCheck { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Cherry"); // Check if key 2 exists boolean keyExists = map.containsKey(2); System.out.println("Key 2 exists: " + keyExists); // Check if value "Banana" exists boolean valueExists = map.containsValue("Banana"); System.out.println("Value 'Banana' exists: " + valueExists); } }
Explanation:
containsKey(2) checks if the key 2 exists in the HashMap.
containsValue(“Banana”) checks if the value “Banana” exists.
Output:
Key 2 exists: true Value 'Banana' exists: true
6. Iterating over a HashMap
There are several ways to iterate over a HashMap, using forEach(), entrySet(), or key and value sets.
Using forEach() Method:
import java.util.HashMap; public class IterateHashMap { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("John", 25); map.put("Alice", 30); map.put("Bob", 22); // Iterate using forEach map.forEach((key, value) -> System.out.println(key + ": " + value)); } }
Explanation:
forEach() method is a convenient way to iterate over each key-value pair.
Output:
John: 25 Alice: 30 Bob: 22
Using entrySet():
import java.util.HashMap; import java.util.Map; public class IterateEntrySet { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Cherry"); // Iterate using entrySet for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); } } }
Explanation:
entrySet() returns a set of key-value pairs (Map.Entry objects), which allows iteration.
Output:
Key: 1, Value: Apple Key: 2, Value: Banana Key: 3, Value: Cherry
7. Replacing a Value in HashMap
You can use the replace() method to update the value associated with a specific key.
Example:
public class ReplaceValue { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Cherry"); // Replacing value of key 2 map.replace(2, "Blueberry"); // Displaying the updated HashMap System.out.println("Updated HashMap: " + map); } }
Explanation:
The replace() method updates the value associated with key 2 from “Banana” to “Blueberry”.
Output: Updated HashMap: {1=Apple, 2=Blueberry, 3=Cherry}.
8. Checking the Size of the HashMap
You can use the size() method to find out how many key-value pairs are stored in the HashMap.
Example:
public class HashMapSize { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("John", 25); map.put("Alice", 30); map.put("Bob", 22); // Checking the size of the HashMap int size = map.size(); System.out.println("Size of HashMap: " + size); } }
Explanation:
size() returns the number of key-value pairs in the HashMap.
Output: Size of HashMap: 3.
9. Clearing a HashMap
You can clear all entries from a HashMap using the clear() method.
Example:
public class ClearHashMap { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("John", 25); map.put("Alice", 30); map.put("Bob", 22); // Clearing the HashMap map.clear(); // Checking if HashMap is empty System.out.println("Is HashMap empty? " + map.isEmpty()); } }
Explanation:
The clear() method removes all entries from the HashMap.
Output: Is HashMap empty? true.
10. HashMap with Custom Objects
You can use custom objects as keys or values in a HashMap, but it’s important to override the equals() and hashCode() methods when using objects as keys.
Example:
import java.util.HashMap; import java.util.Objects; class Employee { String name; int id; public Employee(String name, int id) { this.name = name; this.id = id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Employee employee = (Employee) o; return id == employee.id && Objects.equals(name, employee.name); } @Override public int hashCode() { return Objects.hash(name, id); } } public class HashMapCustomObjects { public static void main(String[] args) { HashMap<Employee, String> map = new HashMap<>(); Employee e1 = new Employee("John", 1); Employee e2 = new Employee("Alice", 2); map.put(e1, "Manager"); map.put(e2, "Developer"); // Displaying the HashMap map.forEach((key, value) -> System.out.println(key.name + ": " + value)); } }
Explanation:
Custom Employee objects are used as keys in the HashMap.
It is essential to override equals() and hashCode() so that HashMap can correctly identify and compare keys.
Output:
John: Manager Alice: Developer
Conclusion
HashMap is a powerful and flexible data structure in Java for storing key-value pairs. It provides efficient methods for accessing, inserting, and removing elements.
By using the operations above, you can handle data effectively with minimal code.