Introduce Java HashMap and give examples
In Java, a HashMap
is part of the Java Collections Framework and is used to store data in key-value pairs. It implements the Map
interface and provides a way to store and retrieve data efficiently. The HashMap
allows for null values and one null key, and it does not maintain any order of its elements.
HashMap
consists of a key and a value.HashMap
is not synchronized, which means it is not thread-safe. If multiple threads access a HashMap
concurrently, it must be synchronized externally.Here are some common operations you can perform with a HashMap
:
Here’s a simple example demonstrating the use of HashMap
in Java:
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Creating a HashMap
HashMap<String, Integer> map = new HashMap<>();
// Adding elements to the HashMap
map.put("Alice", 30);
map.put("Bob", 25);
map.put("Charlie", 35);
map.put(null, 40); // Adding a null key
map.put("David", null); // Adding a null value
// Accessing elements
System.out.println("Alice's age: " + map.get("Alice")); // Output: 30
System.out.println("Bob's age: " + map.get("Bob")); // Output: 25
System.out.println("Age of null key: " + map.get(null)); // Output: 40
System.out.println("David's age: " + map.get("David")); // Output: null
// Removing an element
map.remove("Charlie");
System.out.println("After removing Charlie: " + map);
// Iterating over the HashMap
System.out.println("Iterating over HashMap:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Checking if a key exists
if (map.containsKey("Alice")) {
System.out.println("Alice is in the map.");
}
// Checking if a value exists
if (map.containsValue(25)) {
System.out.println("There is a person aged 25 in the map.");
}
// Size of the HashMap
System.out.println("Size of the map: " + map.size());
}
}
HashMap
that maps String
keys to Integer
values.put()
method to add key-value pairs to the map.get()
method.remove()
method.containsKey()
and containsValue()
.size()
method.HashMap
is a powerful and flexible data structure in Java that allows for efficient storage and retrieval of data in key-value pairs. It is widely used in various applications due to its performance and ease of use.