HashMap
The HashMap
class in Java is an implementation of the Map
interface that stores key-value pairs. It provides fast access and retrieval of elements based on their keys.
To use the HashMap class, you need to import the java.util.HashMap
package.
Here's an example that demonstrates the usage of the HashMap class:
TEXT/X-JAVA
1class Main {
2
3 public static void main(String[] args) {
4 // Create a HashMap
5 HashMap<String, Integer> hashMap = new HashMap<>();
6
7 // Add key-value pairs to the HashMap
8 hashMap.put("John", 25);
9 hashMap.put("Sarah", 30);
10 hashMap.put("Emily", 28);
11
12 // Access values from the HashMap
13 int johnAge = hashMap.get("John");
14 System.out.println("John's age: " + johnAge);
15
16 // Check if a key exists in the HashMap
17 boolean exists = hashMap.containsKey("Sarah");
18 System.out.println("Sarah exists: " + exists);
19
20 // Remove a key-value pair from the HashMap
21 hashMap.remove("Emily");
22
23 // Update the value for a key in the HashMap
24 hashMap.put("John", 26);
25
26 // Get the size of the HashMap
27 int size = hashMap.size();
28 System.out.println("Size of the HashMap: " + size);
29 }
30
31}
xxxxxxxxxx
33
}
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// Create a HashMap
HashMap<String, Integer> hashMap = new HashMap<>();
// Add key-value pairs to the HashMap
hashMap.put("John", 25);
hashMap.put("Sarah", 30);
hashMap.put("Emily", 28);
// Access values from the HashMap
int johnAge = hashMap.get("John");
System.out.println("John's age: " + johnAge);
// Check if a key exists in the HashMap
boolean exists = hashMap.containsKey("Sarah");
System.out.println("Sarah exists: " + exists);
// Remove a key-value pair from the HashMap
hashMap.remove("Emily");
// Update the value for a key in the HashMap
hashMap.put("John", 26);
// Get the size of the HashMap
int size = hashMap.size();
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment