HashMap is a class that implements the Map interface.
Denoted by HashMap<Key, Value> or HashMap<K, V>
It stores the data in (Key, Value) pairs. The key in a hashmap is always unique.
Map<Integer, String> myMap = new HashMap<>();
The internal implementation of HashMap is hashtable based and it implements Serializable, Cloneable, Map<K, V> interfaces. This implementation provides all the optional map operations and permits null values and the null key. However, we can have a single null key in HashMap. This implementation provides constant-time performance for the basic operations (get and put), assuming that the hash function segregates the elements properly among the buckets.
The HashMap implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. This can be either done by traditional multithreading methods or it can also be done using Collections.synchronizedMap method
Map m = Collections.synchronizedMap(new HashMap(...));
We can use the put() and the get() method of hashmap to insert the (key, value ) pair and retrieve the value for a particular key.
package coderoversduo;
import java.util.HashMap;
public class HashMapExm {
public static void main(String[] args) {
// Create an empty hash map
HashMap<Integer, String> myMap = new HashMap<>();
// Adding Elements To The Map Using put() method
myMap.put(1, "Delhi");
myMap.put(2, "Mumbai");
myMap.put(3, "Kolkata");
System.out.println(myMap);
// Iterate Through The Map To Fetch Values
for (Integer key : sampleMap.keySet()) {
System.out.println("Value for Key: " + key + " Is " + sampleMap.get(key));
}
}
}
OUTPUT :
An instance of HashMap has two parameters - initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed to the percentage amount of the load factor. The default load factor is 0.75.
HashMap() - No Arg Constructor.
HashMap(int initialCapacity) - Creates a HashMap with the specified initial capacity. The load factor is 0.75 by default.
HashMap(int initialCapacity, float loadFactor): Creates a HashMap with the specified initial capacity and load factor.
put() - Associates the specified value with the specified key in this map.
entrySet() - Returns a Set view of the mappings contained in this map.
get() - Returns the value to which the specified key is mapped,.
equals() - Compares the specified object with this map for equality.
remove() - Removes the mapping for the specified key from this map if present.
containsKey() - Returns true if this map contains a mapping for the specified key.
containsValue() - Returns true if this map contains a mapping for the specified value.
size() - Returns the number of key-value mappings in this map.
keySet() - Returns a Set view of the keys contained in this map.
isEmpty() - Returns true if this map contains no key-value mappings.
clear() - Removes all of the mappings from this map.
The code below demonstrates the operations that can be done using HashMap.
package coderoversduo;
import java.util.HashMap;
import java.util.Map;
public class HashMapMethodDemo {
public static void main(String[] args) {
Map<Integer, String> sampleMap = new HashMap<>();
// Insert Key Value inside the HashMap
sampleMap.put(1, "SampleOne");
sampleMap.put(2, "SampleTwo");
sampleMap.put(3, "SampleThree");
sampleMap.put(4, "SampleFour");
// Iterate Through The Map To Fetch Values
for (Integer key : sampleMap.keySet()) {
System.out.println("Value For Key: " + key + " Is " + sampleMap.get(key) + ".");
}
// Remove Entry From HashMap Whose Key=4
sampleMap.remove(4);
System.out.println("Removed The Entry With Key =4");
// Check Size Of HasMap
int sizeOfMap = sampleMap.size();
System.out.println("Size Of HashMap Is ::" + sizeOfMap);
// Check equals Method
if (sampleMap.get(1).equals("Sample One")) {
System.out.println("Both the Values Are Equal");
}
// Check isEmpty()
if (sampleMap.isEmpty()) {
System.out.println("Map is Empty");
} else {
System.out.println("Map is not Empty");
}
// Check containsKey() method
if (sampleMap.containsKey(2)) {
System.out.println("Map Contains The Specified Key");
}
}
}
HashMap contains unique Keys.
If you try to insert a key that is already present in the map, the old value corresponding to the key gets overridden by the new value.
You can insert a single null entry as a key but multiple null entries as a value.
Insertion order is not preserved. If you want to preserve the insertion order, you should opt for a LinkedHashMap
Click here to Read More About HashMaps