HashMap in Java is a data structure that stores key-value pairs and allows for fast retrieval of values based on their keys. It belongs to the java.util package and implements the Map interface, providing methods to manipulate and access elements efficiently. Here’s an overview of the syntax, methods, and an example demonstrating the use of HashMap.
import java.util.HashMap;
// Syntax for creating a HashMap
HashMap<KeyType, ValueType> mapName = new HashMap<>();
Code language: JavaScript (javascript)
Method | Description |
---|---|
put(K key, V value) |
Inserts a key-value pair into the map. If the key already exists, updates value. |
get(Object key) |
Returns the value associated with the key, or null if the key is not found. |
remove(Object key) |
Removes the key-value pair for the specified key. |
clear() |
Removes all key-value pairs from the map. |
containsKey(Object key) |
Returns true if the map contains the specified key. |
containsValue(Object value) |
Returns true if the map maps one or more keys to the specified value. |
isEmpty() |
Returns true if the map contains no key-value mappings. |
size() |
Returns the number of key-value pairs in the map. |
🔹 Advanced and Utility Methods
Method | Description |
---|---|
putIfAbsent(K key, V value) |
Inserts the value only if the key is not already associated with a value. |
replace(K key, V value) |
Replaces the value for the specified key if it is present. |
replace(K key, V oldValue, V newValue) |
Replaces the value only if it is currently mapped to the specified old value. |
getOrDefault(Object key, V defaultValue) |
Returns the value for key or the default if key is not present. |
keySet() |
Returns a Set view of the keys contained in the map. |
values() |
Returns a Collection view of the values contained in the map. |
entrySet() |
Returns a Set view of key-value pairs (Map.Entry objects). |
forEach(BiConsumer<K, V>) |
Performs the given action for each key-value pair in the map. |
compute(K key, BiFunction) |
Recalculates the value for a key using a function. |
merge(K key, V value, BiFunction) |
Combines the value for a key using a remapping function. |
import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { // Creating a HashMap to store student names and their roll numbers HashMap<String, Integer> studentMap = new HashMap<>(); // Adding students to the HashMap studentMap.put("Paani", 101); studentMap.put("Mahesh", 102); studentMap.put("Datta", 103); studentMap.put("Ganesh", 104); studentMap.put("Harsha", 105); // Displaying the HashMap System.out.println("HashMap of students:"); System.out.println(studentMap); // Removing a student from the HashMap Integer removedRollNumber = studentMap.remove("Datta"); System.out.println("\nRemoved student 'Datta' with roll number: " + removedRollNumber); // Displaying the updated HashMap System.out.println("\nUpdated HashMap of students:"); System.out.println(studentMap); // Checking if a student exists in the HashMap String searchStudent = "Harsha"; boolean containsStudent = studentMap.containsKey(searchStudent); System.out.println("\nDoes the HashMap contain student '" + searchStudent + "'? " + containsStudent); // Iterating over the entries of the HashMap System.out.println("\nIterating over HashMap entries:"); for (Map.Entry<String, Integer> entry : studentMap.entrySet()) { System.out.println("Student: " + entry.getKey() + ", Roll Number: " + entry.getValue()); } // Size of the HashMap System.out.println("\nSize of the HashMap: " + studentMap.size()); // Clearing the HashMap studentMap.clear(); System.out.println("\nIs the HashMap empty now? " + studentMap.isEmpty()); } }
D:\>javac HashtableExample.java
D:\>java HashtableExample
Hashtable of students:
{Ganesh=104, Paani=101, Mahesh=102, Harsha=105, Datta=103}
Removed student 'Datta' with roll number: 103
Updated Hashtable of students:
{Ganesh=104, Paani=101, Mahesh=102, Harsha=105}
Does the Hashtable contain student 'Harsha'? true
Iterating over Hashtable entries using enumeration:
Student: Ganesh, Roll Number: 104
Student: Paani, Roll Number: 101
Student: Mahesh, Roll Number: 102
Student: Harsha, Roll Number: 105
Size of the Hashtable: 4
Is the Hashtable empty now? true
Code language: JavaScript (javascript)
HashMap in Java is a fundamental data structure for mapping keys to values efficiently. It allows for rapid access, insertion, and removal of elements based on keys, making it suitable for various applications where quick lookups are crucial. Understanding how to utilize HashMap effectively enables developers to design efficient algorithms and manage data effectively in Java applications.