Java HashMap Class
The Java Collections Framework includes HashMap which belongs to the java.util package. HashMap stores data in key-value pairs where keys are required to be unique while values are permitted to have duplicates. A hash table provides the underlying structure for this collection and enables quick operations for inserting, deleting, and finding elements.
Key Features
- Stores key-value pairs
- Keys must be unique
- The data structure permits a single null key while supporting multiple null values.
- Unordered – does not maintain insertion order
- Non-synchronized (not thread-safe)
Syntax
HashMap<KeyType, ValueType> map = new HashMap<>();
Example
HashMap<Integer, String> students = new HashMap<>();
Example
import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { HashMap<Integer, String> employeeMap = new HashMap<>(); // Adding key-value pairs employeeMap.put(1, "Alice"); employeeMap.put(2, "Bob"); employeeMap.put(3, "Charlie"); // Access and modify System.out.println("Employee 2: " + employeeMap.get(2)); employeeMap.put(2, "Bobby"); // Iterating using entrySet for (Map.Entry<Integer, String> entry : employeeMap.entrySet()) { System.out.println(entry.getKey() + " -> " + entry.getValue()); } // Removing an entry employeeMap.remove(3); // Check contents System.out.println("Has key 1? " + employeeMap.containsKey(1)); System.out.println("Has value 'Charlie'? " + employeeMap.containsValue("Charlie")); // Clear the map employeeMap.clear(); System.out.println("Is map empty? " + employeeMap.isEmpty()); } }
Note
- The hashCode() and equals() methods maintain key uniqueness within this data structure.
- Custom objects that serve as map keys require proper implementation of both hashCode() and equals() methods.
- Use LinkedHashMap for insertion-order retention.
- Use TreeMap for sorted key order.
- Use Collections.synchronizedMap() or ConcurrentHashMap for thread-safe versions.
HashMap vs TreeMap vs LinkedHashMap
Feature | HashMap | TreeMap | LinkedHashMap |
---|---|---|---|
Order | No order | Sorted keys | Insertion order |
Null Key | Allowed (1) | Not allowed | Allowed (1) |
Performance | Fastest | Slower | Medium |
Quickly Find What You Are Looking For
Onlinetpoint is optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.