Last Updated: 26 October, 2023
HashMap is a part of the Java Collections Framework, was introduced in the Java 1.2 version, and is available in the java.util package.
HashMap is a data structure in Java that is used to store data in the form of key-value pairs where keys must be unique and values may be duplicated.
HashMap is a child class of the AbstractMap class, and it implements the Map interface as well as the Cloneable and Serializable interfaces.
HashMaps are known for their high efficiency in data storage and retrieval due to their utilization of a hash function, which facilitates the mapping of keys to specific indices within an array. This implies that the operations of lookups, insertions, and deletions can be performed with a constant time complexity of O(1).
Let's see how HashMap stores the data in the form of key-value pairs:
Here, using the Map interface put() method, we are adding data in the form of key and value pairs into the map where each key is bound to each value. A Map contains only unique keys, but values may be duplicated.
Let's see the complete hierarchy of Java Map interfae below.
As we can see from the complete hierarchy above, HashMap extends the AbstractMap class and implements Map, Serializable, and Cloneable interfaces.
Here, K is the key Object type and V is the value Object type.
Output
Iterating Hashmap and printing Key and Value
in - India
en - England
us - United State
ca - Canada
Constructor | Description |
---|---|
HashMap() | Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75). |
HashMap(int initialCapacity) | Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75). |
HashMap(int initialCapacity, float loadFactor) | Constructs an empty HashMap with the specified initial capacity and load factor. |
HashMap(Map extends K,? extends V> m) | Constructs a new HashMap with the same mappings as the specified Map. |
Java HashMap class has the following methods.
Methods and Descriptions |
---|
Removes all of the mappings from this map. The map will be empty after this call returns. |
Returns true if this map maps one or more keys to the specified value. |
Returns a Set view of the keys contained in this map. |
Returns a Collection view of the values contained in this map. |
Returns a Set view of the mappings contained in this map. |
If the specified key is not already associated with a value (or is mapped to null), it attempts to compute its value using the given mapping function and enters it into this map unless it is null. |
If the value for the specified key is present and non-null, it attempts to compute a new mapping given the key and its current mapped value. |
Attempts to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping). |
If the specified key is not already associated with a value or is associated with null, associate it with the given non-null value. |
Returns a shallow copy of this HashMap instance; the keys and values themselves are not cloned. |
The Java HashMap class provided methods are implemented in the below given examples. Let's go through the examples one by one and understand the uses for each method.
Example 1: Methods for Adding Elements to a HashMap
Output
HashMap Elements:{101=C, 102=C++, 103=Java, 104=Python}
After calling putIfAbsent():{101=C, 102=C++, 103=Java, 104=Python, 105=Go Lang}
HashMap Elements after adding another HashMap:
{112=MongoDB, 101=C, 102=C++, 103=Java, 104=Python, 105=Go Lang, 111=MySQL}
Example 2: Methods for Accessing Elements from a HashMap
Output
HashMap Elements:{101=C, 102=C++, 103=Java, 104=Python, 105=Go Lang}
Iterate the map using for-each loop
Key: 101 Value: C
Key: 102 Value: C++
Key: 103 Value: Java
Key: 104 Value: Python
Key: 105 Value: Go Lang
After called map.get(102): C++
Returns a Collection view of the values contained in this map
C
C++
Java
Python
Go Lang
Example 3: Methods for Updating Elements in a HashMap
Output
HashMap Elements:{101=C, 102=C++, 103=Java, 104=Python, 105=Go Lang}
After called map.replace(105, "MySQL"):
{101=C, 102=C++, 103=Java, 104=Python, 105=MySQL}
After called map.replace(103, "Java", "JAVA/J2EE"):
{101=C, 102=C++, 103=JAVA/J2EE, 104=Python, 105=MySQL}
After called map.replaceAll((k,v) -> "MongoDB"):
{101=MongoDB, 102=MongoDB, 103=MongoDB, 104=MongoDB, 105=MongoDB}
Example 4: Methods for Removing Elements from a HashMap
Output
HashMap Elements:{101=C, 102=C++, 103=Java, 104=Python, 105=Go Lang}
After called map.remove(102):{101=C, 103=Java, 104=Python, 105=Go Lang}
Afte called map.remove(104, "Python"):{101=C, 103=Java, 105=Go Lang}
After called map.remove(101, "C++"):{101=C, 103=Java, 105=Go Lang}
After called map.clear():{}
Example 5: Utility Methods of HashMap
Output
HashMap Elements:{101=C, 102=C++, 103=Java, 104=Python}
HashMap Size: 4
Is Map is Empty: false
map.containsKey(105): false
map.containsValue("Java"): true
After calling map.clear():{}
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/HashMap
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com
What is the difference between HashMap and TreeMap?
Ans. HashMap and TreeMap are implementations of the Map interface in Java, and both are by default synchronised classes and available in the java.util package. There are many differences between the HashMap and TreeMap classes. Lets look at those differences in the below-given table:
HashMap | TreeMap |
---|---|
HashMap is a hashtable-based implementation of the Map interface. | TreeMap is a tree-structure-based (internally, it uses a Red-Black tree) implementation of the NavigableMap interface. |
HashMap implements the Map, Cloneable, and Serializable interfaces. | TreeMap implements the NavigableMap, Cloneable, and Serializable interfaces. |
HashMap allows only one null key and multiple null values. | TreeMap does not allow null keys but can have multiple null values. |
HashMap does not maintain the insertion order of elements. | TreeMap elements are sorted in natural order (ascending). |
HashMap uses the equals() method of the Object class to compare keys. The equals() method of the Map class overrides it. | TreeMap uses the compareTo() method to compare keys. |
HashMap allows heterogeneous elements because it does not perform sorting on keys. | TreeMap allows homogeneous values as a key because of sorting. |
HashMap is much faster than TreeMap. | In comparison to HashMap, TreeMap is slower. |
HashMap contains only basic functions. | TreeMap is rich in functionality. |
The HashMap should be used when we do not require key-value pairs in sorted order. | The TreeMap should be used when we require key-value pairs in sorted (ascending) order. |
What is the difference between HashMap and LinkedHashMap?
HashMap | LinkedHashMap |
---|---|
HashMap extends the AbstractMap class. | LinkedHashMap extends the HashMap class. |
HashMap does not maintain the insertion order of elements. | The insertion order of elements is preserved by LinkedHashMap. (Major Difference) |
HashMap uses hash tables to store maps. | LinkedHashMap uses a hash table along with a linked list to store maps. |
HashMap was introduced in the JDK 1.2 version. | LinkedHashMap was introduced in the JDK 1.4 version. |
HashMap required less memory than LinkedHashMap. | LinkedHashMap required more memory than LinkedHashMap. |
HashMap gives faster performance than LinkedHashMap. | LinkedHashMap's performance is a bit slower than HashMap's. |
How to synchronize a HashMap in Java?
Ans. HashMap is by default not synchronized, but using the method synchronizedMap() of the java.util.Collections class, we synchronized the HashMap in Java.
Lets see the implementation below.
import java.util.Collections; import java.util.HashMap; import java.util.Map; public class SynchronizedHashMap { public static void main(String[] args) { HashMapmap = new HashMap (); Map syncMap = Collections.synchronizedMap(map); } }
What is the difference between HashMap and Hashtable?
HashMap and Hashtable both implement the Map interface and accept values in the form of key-value pairs. Both the classes look similar, but there are many differences between them. Let's see the below given table.
Comparison Parameters | HashMap Vs Hashtable |
---|---|
Synchronized | HashMap is not synchronized by default, whereas HashTable is by default synchronized. |
Thread Safe | HashMap is not thread safe, whereas HashTable is thread safe. |
Null keys and null values | Hashmap allows one null key and any number of null values, whereas Hashtable does not allow null keys or null values. |
Iterating the values | Hashmap object values are iterated by using an iterator, whereas HashTable is the only class other than vector that uses an enumerator to iterate the values of HashTable objects. |
Fail-fast iterator | The iterator in Hashmap is a fail-fast iterator, while the enumerator for Hashtable is not. If the Hashtable is structurally modified at any time after the iterator is created in any way except the iterator's own remove method, then the iterator will throw a Note: Structural modification means adding or removing elements from the Collection object. Thus, the enumerations returned by the Hashtable keys and elements methods are not fail-fast. |
Performance | Hashmap is much faster and uses less memory than Hashtable as the former is unsynchronized. In a single-threaded environment, unsynchronized objects are often much better in performance when compared to synchronized objects like hashtables. |
Superclass | Hashtable is a subclass of the Dictionary class, which is now obsolete in JDK 1.7, so it is not used anymore. It is better off externally synchronizing a HashMap or using a ConcurrentMap implementation (e.g., ConcurrentHashMap). HashMap is a subclass of the AbstractMap class. Although Hashtable and HashMap have different superclasses, they are both implementations of the "Map" abstract data type. |
Legacy Class | HashMap is not a legacy class, whereas Hashtable is a legacy class in Java. |
Introduced | HashMap was introduced in the JDK 1.2 version, whereas Hashtable was introduced in the JDK 1.0 version. |
What is the difference between HashMap and WeakHashMap in Java?
Ans. WeakHashMap is almost similar to the HashMap class in Java. The major difference is that an entry in a WeakHashMap will automatically be removed by the garbage collector when its key is no longer in ordinary use.
Let us examine the differences between the HashMap and WeakHashMap using the table below.
HashMap | WeakHashMap |
---|---|
The stored entry object is not eligible for garbage collection. | An entry in a WeakHashMap will be automatically removed when its key loses all strong and soft references. |
HashMap holds strong references to its key objects. | Weak references to keys are stored in the case of a WeakHashMap. |
The size() method will always return the same value unless we explicitly add or remove entries. | The size() method may return a smaller value as a few entries might be automatically removed by the GC. |
HashMap implements a Serializable interface. | WeakHashMap does not implement the Serializable interface. |
The Cloneable interface is implemented by the HashMap, and its clone() method returns a shallow copy of the HashMap. | It does not implement a clonable interface. |
What is the difference between HashSet and HashMap in Java?
Ans. HashSet and HashMap have the following differences, as shown in the below table:
HashSet | HashMap |
---|---|
HashSet implements the Set interface. | HashMap implements the Map interface. |
HashSet is an unordered collection of elements that contains only unique elements. | HashMap stores elements in the form of key and value pairs and, keys must be unique. If the key is duplicated then the old key is replaced with the new value. |
HashSet implements Set, Cloneable, Serializable, Iterable and Collection interfaces. | HashMap implements Map, Cloneable, and Serializable interfaces. |
HashSet requires just one parameter for its object initialization. | HashMap requires two parameters (key and value) for its object initialization. |
HashSet can contain a single null value. | HashMap can contain a single null key and no restriction on any number of null values. |
For additing the element we use add() method. | Here, we use the put() method for adding an element. |
HashSet internally uses the HashMap object to store or add objects. | HashMap internally uses hashing to store or add objects. |
HashSet performance is slower than HashMap. | HashMap performance is faster than HashSet. |