HashMap in Java is a powerful data structure that provides the implementation of the Map interface, storing data in (Key, Value) pairs. Unlike HashSet, which only stores the key, HashMap stores both the key-value pairs. The performance of HashMap depends on two parameters, namely the initial capacity and the load factor.
Some important features of HashMap are:
- It is a part of java.util package.
- It extends an abstract class AbstractMap, which provides an incomplete implementation of the Map interface.
- It does not allow duplicate keys but allows duplicate values, which means a single key cannot contain more than one value but more than one key can contain a single value.
- It does not maintain the track and order of insertion of elements.
Some important methods of HashMap and their working are as follows:
- put(Object key, Object value): This method is used to insert a specific mapping of key-value pair into a map. It has an average time complexity of O(1).
- size(): This method returns the size of a map and has a worst-case time complexity of O(1).
- isEmpty(): This method is used to check whether the map is empty or not. It returns true if the map is empty and has a worst-case time complexity of O(1).
- containsKey(Object key): This method returns true if, for a specified key, mapping is present in the map. It has an average time complexity of O(1).
- remove(Object key): This method is used to remove a particular key in the Map and returns the corresponding value. If the key is not present, the function returns Null. It has an average time complexity of O(1).
- containsValue(Object value): This method returns true if one or more keys are mapped to a specified value. It has a worst-case time complexity of O(n).
- get(Object key): This method is used to retrieve or fetch the value mapped by a particular key. If the key is not found, it returns Null. It has an average time complexity of O(1).
Let's take a look at some examples to understand the working of HashMap better.
Example 1: Working of put(), size() and Traversal of HashMap.
javaimport java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args)
{
// Create an empty hash map
HashMap<String, Integer> m
= new HashMap<>();
// Add elements to the map
m.put("gfg", 10);
m.put("ide", 15);
m.put("courses", 20);
// Print size and content
System.out.println(m);
System.out.println(m.size());
// Iterating over HashMap
for(Map.Entry<String, Integer> e : m.entrySet())
System.out.println(e.getKey() + " " + e.getValue());
}
}
Output:
{courses=20, gfg=10, ide=15}
3
courses 20
gfg 10
ide 15
Note: The order of output in key-value pairs may vary.
Example 2: Working of containsKey() and remove().
```java
import java.util.HashMap;
public class HashMapExample {
public static void main(String[] args)
{
// Create an empty hash map
HashMap<String, Integer> m
= new HashMap<>();
// Add elements to the map
m.put("gfg", 10);
m.put("ide", 15);
m.put("courses", 20);
// Check for a key
if (m.containsKey("ide"))
System.out.println("The key 'ide' is present in the HashMap."); else System.out.println("The key 'ide' is not present in the HashMap.");// Remove the key 'ide' and get the value associated with it int value = m.remove("ide");
System.out.println("Value associated with key 'ide': " + value);
// Check for a value
if (m.containsValue(20))
System.out.println("The value 20 is present in the HashMap.");
else
System.out.println("The value 20 is not present in the HashMap.");
// Get the value associated with the key 'gfg'
int gfgValue = m.get("gfg");
System.out.println("Value associated with key 'gfg': " + gfgValue);
// Print the size of the HashMap
System.out.println("Size of HashMap: " + m.size());
// Iterate over the HashMap
System.out.println("Iterating over HashMap:");
for(Map.Entry<String, Integer> entry : m.entrySet()) {
String key = entry.getKey();
int val = entry.getValue();
System.out.println(key + " : " + val);
}
}}
Output: The key 'ide' is present in the HashMap. Value associated with key 'ide': 15 The value 20 is present in the HashMap. Value associated with key 'gfg': 10 Size of HashMap: 2 Iterating over HashMap: courses : 20 gfg : 10
In the above example, we first create an empty HashMap using the constructor with no arguments. We then add three key-value pairs to the HashMap using the put() method.
Next, we use the containsKey() method to check if the key "ide" is present in the HashMap. We then use the remove() method to remove the key "ide" from the HashMap and get the value associated with it.
We then use the containsValue() method to check if the value 20 is present in the HashMap. Next, we use the get() method to get the value associated with the key "gfg".
We then print the size of the HashMap using the size() method. Finally, we iterate over the HashMap using the entrySet() method and print each key-value pair using a for-each loop.
Overall, HashMap is a useful data structure in Java for storing and retrieving data efficiently using key-value pairs.