A HashMap is a part of Java’s Collection Framework and implements the Map interface. It stores elements in key-value pairs, where, Keys are unique. and Values can be duplicated.
- Internally uses Hashing, hence allows efficient key-based retrieval, insertion, and removal with an average of O(1) time.
- HashMap is not thread-safe, to make it synchronized, use Collections.synchronizedMap().
- Insertion order is not preserved in HashMap. To preserve the insertion order, LinkedHashMap is used and to maintain sorted order, TreeMap is used.
HashMap Declaration;
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
It takes two parameters, namely as follows:
- K -> Type of keys maintained by this map
- V -> Type of mapped values
import java.util.HashMap;
import java.util.Map;
public class GFG{
public static void main(String[] args){
// Create a HashMap
HashMap<String, Integer> hashMap = new HashMap<>();
// Add elements to the HashMap
hashMap.put("John", 25);
hashMap.put("Jane", 30);
hashMap.put("Jim", 35);
// Iterate through the HashMap
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
}
}
Output
John -> 25 Jane -> 30 Jim -> 35
Hierarchy of HashMap in Java
It extends AbstractMap and implements the Map Interface.