In Java, a HashMap is a data structure that stores key-value pairs in a hash table. It is part of the java.util package and provides methods to add, remove, and access elements in the map.
Here’s an example that demonstrates how to use a HashMap:
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Create a HashMap of student names and their ages
Map<String, Integer> students = new HashMap<>();
// Add elements to the HashMap
students.put("Alice", 18);
students.put("Bob", 19);
students.put("Charlie", 20);
students.put("David", 21);
// Get the size of the HashMap
int size = students.size();
System.out.println("Size of HashMap: " + size);
// Access elements in the HashMap
int aliceAge = students.get("Alice");
System.out.println("Alice's age: " + aliceAge);
// Modify an element in the HashMap
students.put("Bob", 20);
System.out.println("Modified HashMap: " + students);
// Remove an element from the HashMap
students.remove("Charlie");
System.out.println("HashMap after removing an element: " + students);
// Check if a key is present in the HashMap
boolean contains = students.containsKey("David");
System.out.println("HashMap contains David: " + contains);
// Iterate over the elements in the HashMap
for (Map.Entry<String, Integer> entry : students.entrySet()) {
String name = entry.getKey();
int age = entry.getValue();
System.out.println("Name: " + name + ", Age: " + age);
}
// Clear the HashMap
students.clear();
System.out.println("HashMap after clearing all elements: " + students);
}
}
In this example, we create a HashMap of student names and their ages using the HashMap class and add four key-value pairs to it using the put() method. We then use the size() method to get the size of the HashMap and the get() method to access the value of a key.
We also demonstrate how to modify a value using the put() method, remove a key-value pair using the remove() method, check if a key is present in the HashMap using the containsKey() method, and iterate over the key-value pairs using a for-each loop and the entrySet() method.
Finally, we use the clear() method to remove all key-value pairs from the HashMap.
The output of this example might look something like this:
Size of HashMap: 4
Alice's age: 18
Modified HashMap: {Alice=18, Bob=20, David=21}
HashMap after removing an element: {Alice=18, Bob=20, David=21}
HashMap contains David: true
Name: Alice, Age: 18
Name: Bob, Age: 20
Name: David, Age: 21
HashMap after clearing all elements: {}
HashMap provides several advantages over traditional arrays and other data structures like ArrayList, including faster access and modification of elements. However, HashMap may not preserve the order of the elements, and duplicates are not allowed for the keys. In such cases, LinkedHashMap may be used instead.