Interview Kickstart has enabled over 21000 engineers to uplevel.
If you’re aiming to crack the world’s most challenging coding interviews, HashMap is an essential concept to have in your toolkit. In this article, we’ll discuss HashMaps, as used in Java, along with some examples.
In this article, we’ll cover:
HashMap<K, V> is a class we can find in the Java.util package. The HashMap class is the implementation of the Map interface of Java and consists of key-value pairs. We denote it by <Key, Value> pair; we can access it using the key, i.e., one must know the key to access the value stored at that key in HashMap.
A HashMap allocates unique keys to corresponding values, which we can access at any point. It stores elements in key-value pairs. Keys are unique identifiers used to link each value on a map. It will replace the value of the corresponding key on trying to insert a duplicate key.
The HashMap uses a "Hashing" technique. Hashing involves the conversion of a longer string into a shorter string by applying some algorithm to it. The string is converted to a shorter string as it makes the searching process faster.
public class HashMap<Key,Value> extends AbstractMap<Key,Value>implements Map<Key,Value>, Cloneable, Serializable
Class Parameters:
We can declare the Map in the following ways:
HashMap<Key,Value> myMap1 = new HashMap<Key,Value>();
HashMap myMap2 = new HashMap();
Here is the example containing the declaration of HashMap in java.
Code:
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// Creating HashMap.
HashMap<String, Integer> myMap= new HashMap<>();
/*
It can be also declared like: HashMap<String, Integer> myMap= new HashMap<String, Integer>();
*/
// Adding Elements to the HashMap
myMap.put("IK", 1);
myMap.put("HM", 2);
myMap.put("TM", 3);
// Printing HashMap
System.out.println("myMap: " + myMap);
}
}
Output:
myMap: {IK=1, HM=2, TM=3}
List of some methods available for class HashMap in Java.
Here is an example containing the implementation of some basic methods of HashMap.
Code:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Creating HashMap.
HashMap<String, Integer> myMap= new HashMap<>();
// put() method to add elements in the HashMap.
myMap.put("IK", 1);
myMap.put("HM", 2);
myMap.put("TM", 3);
// Printing HashMap
System.out.println("HashMap: " + myMap);
// get() method to get value associated with a particular key.
String key = "IK";
int val= myMap.get(key);
System.out.println("Value related to key IK: " + val);
// Using keySet() to return a set view of keys.
System.out.println("Keys: " + myMap.keySet());
// Using values() to return a set view of values.
System.out.println("Values: " + myMap.values());
// Using entrySet() to return a set view of key/value pairs.
System.out.println("Key/Value mappings: " + myMap.entrySet());
System.out.println("Original HashMap: " + myMap);
// Changing element with key IK.
myMap.replace("IK", 5);
System.out.println("HashMap after using replace(): " + myMap);
// Remove elements associated with the key IK.
val = myMap.remove("IK");
System.out.println("Removed value: " + val);
System.out.println("Updated HashMap: " + myMap);
}
}
Output:
HashMap: {IK=1, HM=2, TM=3}
Value related to key IK: 1
Keys: [IK, HM, TM]
Values: [1, 2, 3]
Key/Value mappings: [IK=1, HM=2, TM=3]
Original HashMap: {IK=1, HM=2, TM=3}
HashMap using replace(): {IK=5, HM=2, TM=3}
Removed value: 5
Updated HashMap: {HM=2, TM=3}
We need to see some key terms before studying this topic:
Initial Capacity: Capacity of the Map at the time of its creation.
Load Factor: Percentage value of the Map’s capacity, after which we need the capacity of Hashmap to increase.
HashMap provides four constructors, and the access modifier of each is public:
There are many ways to Iterate through HashMap. You can study them here in detail.
The time complexity is constant for basic operations like get and put — O(1).
Iterating over HashMap takes linear time complexity, i.e., O(n). As we are visiting each key-value pair and Iterating till the last element of the map, it is directly proportional to the sum: capacity + size of the Map.
HashMap, at its core, is the implementation of Hashing. So, it can be useful where we need efficient implementation of operations like search, insert and delete.
It is used in the effective implementation of some useful algorithms like Dijkstra's Algorithm and Topological Sort.
In Java, we can create a HashMap from other Maps.
Let’s imagine we already have created an object of Class TreeMap named myTreeMap.
Now, we will create an object of HashMap named myHashMap using the TreeMap.
HashMap<String, Integer> myHashMap= new HashMap<(myTreeMap);
The newly created myHashMap will contain all the key-value pairs of myTreeMap.
Code:
import java.util.HashMap;
import java.util.TreeMap;
class Main {
public static void main(String[] args) {
// Creating a Tree Map
TreeMap<String, String> myTreeMap= new TreeMap<>();
// Inserting Elements.
myTreeMap.put("IK", "InterviewKickstart");
myTreeMap.put("TM", "TreeMap");
// Printing the TreeMap
System.out.println("TreeMap: " + myTreeMap);
// Creating HashMap from the TreeMap
HashMap<String, String> myHashMap= new HashMap(myTreeMap);
// Inserting new key-value pair in HashMap.
myHashMap.put("HM", "HashMap");
// Printing the HashMap
System.out.println("HashMap: " + myHashMap);
}
}
Output:
TreeMap: {IK = InterviewKickstart, TM = TreeMap}
HashMap: {IK = InterviewKickstart, TM = TreeMap, HM = HashMap}
Example
{1 -> a, 2 -> b, 3 -> c, 4 -> d}
{'a', 'b', 'c'}
For more commonly asked interview questions at FAANG and tier-1 tech companies, visit the Interview Questions page.
In HashMap, the key or value object must implement the equals() and hashcode() method.
Because, When we insert the key object into the map, we need to use hashcode() there, while we need the equals() method when we try to get the value from the map.
The hashcode() method returns the integer value generated by the hashing algorithm, while the equals() method compares two strings based on the content of the strings.
Yes, we can store the null key because Java HashMap allows one null key. That will be stored at the first location of the bucket array here because hashCode() will throw NullPointerException on calling it on the null key. So, HashMap doesn't call the hashCode() method for the null key. Hence, when the user null calls the get() method, the value at the first index is returned.
No, we can not store the duplicate key in the HashMap. Java HashMap doesn't allow duplicate keys. If we try to insert an existing key with some value, it will replace the old value. But here, the size of HashMap will not change.
Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!
If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of Software Engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!
————
Article contributed by Omkar Deshkmukh
Attend our webinar on
"How to nail your next tech interview" and learn