Tutorial Playlist
HashMap in Java is an integral part of the collections framework. It is located in the java.util package. It implements the Java Map interface in its most basic form. It saves the data as a key-value mapping, where each key corresponds to exactly one data type value. Here is a tutorial blog on how to use HashMap in Java.
This will cover the concepts of hierarchy in HashMap, different chrematistics of HashMap, constructors in HashMap, the internal structure of HashMap, advantages of HashMap, disadvantages of HashMap, and the basic usage of HashMap in Java, among others.
Here are some of the HashMap methods in Java:
Method | Description |
HashMap() | Constructs an empty HashMap. |
HashMap(int initialCapacity) | Constructs an empty HashMap with the specified initial capacities and the default load factor. |
HashMap(int initialCapacity, float loadFactor) | Constructs an empty HashMap with the specified initial capacity and load factor. |
clear() | Removes all key-value mappings from the HashMap. |
clone() | Returns a shallow copy of the HashMap instance. |
containsKey(Object key) | Returns true if the HashMap contains a mapping for the specified key. |
containsValue(Object value) | Returns true if the HashMap contains at least one mapping with the specified value. |
entrySet() | Returns a Set view of the key-value mappings in the HashMap. |
get(Object key) | Returns the value to which the specified key is mapped or null if the key is not present in the HashMap. |
isEmpty() | Returns true if the HashMap contains no key-value mappings. |
keySet() | Returns a Set view of the keys in the HashMap. |
put(K key, V value) | Associates the specified value with the specified key in the HashMap. If the key already exists, the previous value is replaced. |
putAll(Map<? extends K, ? extends V> m) | Copies all of the mappings from the specified map to the HashMap. |
remove(Object key) | Removes the mapping for the specified key from the HashMap if it is present. |
size() | Returns the number of key-value mappings in the HashMap. |
values() | Returns a Collection view of the values in the HashMap. |
Method | Description |
equals() | Compares the specified object with the HashMap for equality. |
hashCode() | Returns the hash code value for the HashMap. |
toString() | Returns a string representation of the HashMap object. |
Method | Description |
equals() | Compares the specified object with the HashMap for equality. |
hashCode() | Returns the hash code value for the HashMap. |
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args) {
// Create a new HashMap
HashMap<String, Integer> studentGrades = new HashMap<>();
// Add key-value pairs to the HashMap
studentGrades.put("Alice", 95);
studentGrades.put("Bob", 80);
studentGrades.put("Charlie", 75);
// Print the HashMap
System.out.println(studentGrades);
}
}
In this example, we create a new HashMap called studentGrades that maps String keys (student names) to Integer values (grades).
We use the put() method to add key-value pairs to the HashMap. In this case, we add three entries: "Alice" with a grade of 95, "Bob" with a grade of 80, and "Charlie" with a grade of 75.
Finally, we print the HashMap using System.out.println(), which displays the key-value pairs enclosed in curly braces.
Here is an example demonstrating various operations on a HashMap within a single program:
import java.util.HashMap;
public class HashMapOperationsExample {
public static void main(String[] args) {
// Create a new HashMap
HashMap<String, Integer> studentGrades = new HashMap<>();
// Add key-value pairs to the HashMap
studentGrades.put("Alice", 95);
studentGrades.put("Bob", 80);
studentGrades.put("Charlie", 75);
// Print the HashMap
System.out.println("HashMap: " + studentGrades);
// Get the value for a specific key
int bobGrade = studentGrades.get("Bob");
System.out.println("Bob's Grade: " + bobGrade);
// Check if a key exists
boolean hasCharlie = studentGrades.containsKey("Charlie");
System.out.println("Does Charlie exist? " + hasCharlie);
// Remove a key-value pair
studentGrades.remove("Alice");
// Check the size of the HashMap
int size = studentGrades.size();
System.out.println("Size of the HashMap: " + size);
// Iterate over the HashMap
System.out.println("Iterating over the HashMap:");
for (String name : studentGrades.keySet()) {
int grade = studentGrades.get(name);
System.out.println(name + "'s Grade: " + grade);
}
// Update a value
studentGrades.put("Bob", 90);
int updatedBobGrade = studentGrades.get("Bob");
System.out.println("Updated Bob's Grade: " + updatedBobGrade);
// Clear the HashMap
studentGrades.clear();
// Check if the HashMap is empty
boolean isEmpty = studentGrades.isEmpty();
System.out.println("Is the HashMap empty? " + isEmpty);
}
}
In this example, we perform various operations on a HashMap called studentGrades:
Each operation is performed within the same program, showcasing different functionalities of a HashMap in Java.
The important features of HashMap in Java are:
These features make HashMap a versatile and widely used data structure in Java for efficiently storing and retrieving key-value pairs.
HashMap internally uses an array of nodes to store key-value pairs. Each node is an instance of an inner class in HashMap. The nodes are organized into buckets, and the number of buckets is called the capacity. The bucket in which a value is stored is determined by the key's hashCode() method.
When retrieving a value, the bucket is calculated using hashCode(), and then the equals() method is used to find the exact match within that bucket.
To avoid having too many buckets with multiple values, the capacity is doubled when 75% of the buckets become non-empty. The load factor triggers this resizing operation. The default load factor is 75%, and the initial capacity is 16, but both can be customized through the constructor.
This internal structure and resizing mechanism of HashMap enable efficient storage and retrieval of key-value pairs while dynamically adapting to the number of elements being stored.
Synchronized HashMap
To create a synchronized version of a HashMap in Java, you can use the Collections.synchronizedMap() method. Here's an example:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class main {
public static void main(String[] args) {
// Create a new HashMap
Map<String, Integer> studentGrades = new HashMap<>();
// Make the HashMap synchronized
Map<String, Integer> synchronizedMap = Collections.synchronizedMap(studentGrades);
// Add key-value pairs to the synchronized HashMap
synchronizedMap.put("Alice", 95);
synchronizedMap.put("Bob", 80);
synchronizedMap.put("Charlie", 75);
// Access values from the synchronized HashMap
synchronized (synchronizedMap) {
for (String name : synchronizedMap.keySet()) {
int grade = synchronizedMap.get(name);
System.out.println(name + "'s Grade: " + grade);
}
}
}
}
In this example, we create a regular HashMap called studentGrades. Then, we use the Collections.synchronizedMap() method to create a synchronized version of the HashMap called synchronizedMap.
We add key-value pairs to the synchronized HashMap using the put() method, just like a regular HashMap.
We synchronize the code block using the synchronized keyword to ensure thread safety when accessing the synchronized HashMap. In this example, we synchronize on the synchronizedMap object.
Within the synchronized block, we iterate over the keys of the synchronized HashMap and retrieve the corresponding values.
Here are some common use cases where HashMap can be applied effectively:
Phonebook: HashMap can be used to implement a phonebook. The names are stored as keys and corresponding phone numbers as values. This allows for efficient retrieval of phone numbers based on names.
Dictionary Application: HashMap is suitable for implementing a dictionary application. The words can be used as keys, and their meanings or descriptions can be stored as values. This enables fast lookup of word definitions based on the provided key (word).
Distributed Caching Systems: Distributed caching systems like Couchbase, Membase, and Redis are essentially extended versions of HashMaps. They provide high concurrency and large-scale data storage through replication and distribution. These systems allow for efficient caching and retrieval of frequently accessed data in distributed environments.
Here are the advantages of HashMap:
Here are the disadvantages of HashMap:
This brief tutorial blog on HashMap will be beneficial for learners in understanding this Java concept better. Enrolling in a certified Java course can help you gain deeper insights into this programming language and understand HashMap better. You can consider courses at reputed online learning platforms such as upGrad.
1.Can a HashMap contain duplicate values?
Yes, HashMap allows duplicate values. HashMap does not allow duplicate keys (keys must be unique). However, it is possible to have multiple entries with the same value.
2. How to print HashMap in Java?
You can print the HashMap in Java using System.out.println().
3. How does HashMap handle collisions?
HashMap handles collisions using a linked list at each bucket (array index) that stores entries with the same hash code but different keys. In HashMap in Java 8, if a bucket contains a certain number of entries (by default, 8), the linked list is converted into a balanced tree for improved performance.
PAVAN VADAPALLI
popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .