The Map interface is an important part of the Java Collections Framework and represents a key-value mapping. It is used to store and retrieve values based on their associated keys.
One of the commonly used implementations of the Map interface is the HashMap class. The HashMap class provides a hash-based mechanism for storing and accessing key-value pairs.
To use the Map interface with the HashMap class, you first need to import the necessary classes:
TEXT/X-JAVA
1import java.util.HashMap;
2import java.util.Map;
Here's an example of using the Map interface with the HashMap class:
TEXT/X-JAVA
1import java.util.HashMap;
2import java.util.Map;
3
4public class Main {
5 public static void main(String[] args) {
6 // Creating a Map
7 Map<String, Integer> studentScores = new HashMap<>();
8
9 // Adding key-value pairs to the Map
10 studentScores.put("Alice", 95);
11 studentScores.put("Bob", 80);
12 studentScores.put("Charlie", 75);
13
14 // Getting the value for a specified key
15 int aliceScore = studentScores.get("Alice");
16
17 // Updating the value for a specified key
18 studentScores.put("Alice", 90);
19
20 // Removing a key-value pair from the Map
21 studentScores.remove("Charlie");
22
23 // Checking if a specified key exists in the Map
24 boolean containsBob = studentScores.containsKey("Bob");
25
26 // Printing the key-value pairs in the Map
27 for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
28 String name = entry.getKey();
29 int score = entry.getValue();
30 System.out.println(name + " - " + score);
31 }
32 }
33}
xxxxxxxxxx
33
}
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// Creating a Map
Map<String, Integer> studentScores = new HashMap<>();
// Adding key-value pairs to the Map
studentScores.put("Alice", 95);
studentScores.put("Bob", 80);
studentScores.put("Charlie", 75);
// Getting the value for a specified key
int aliceScore = studentScores.get("Alice");
// Updating the value for a specified key
studentScores.put("Alice", 90);
// Removing a key-value pair from the Map
studentScores.remove("Charlie");
// Checking if a specified key exists in the Map
boolean containsBob = studentScores.containsKey("Bob");
// Printing the key-value pairs in the Map
for (Map.Entry<String, Integer> entry : studentScores.entrySet()) {
String name = entry.getKey();
int score = entry.getValue();
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment