Mark As Completed Discussion

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}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment