HashMap
In Java, the HashMap
class is a widely used data structure that stores key-value pairs. It provides constant-time performance for basic operations like insertion, deletion, and retrieval.
Creating a HashMap
To create a HashMap
, you need to specify the types of the key and value in angle brackets (<>
). You can use any Java class for the key and value types.
1HashMap<String, Integer> scores = new HashMap<>();
Adding Key-Value Pairs
You can add key-value pairs to the HashMap
using the put()
method. The key and value are specified as parameters to the method.
1scores.put("Alice", 85);
Retrieving Values
You can retrieve a value from the HashMap
using the get()
method. The key is specified as the parameter, and the method returns the corresponding value.
1int aliceScore = scores.get("Alice");
Updating Values
To update the value associated with a key in the HashMap
, you can use the put()
method again. If the key already exists in the HashMap
, the value will be replaced with the new value.
1scores.put("Bob", 92);
Checking if a Key Exists
You can check if a key exists in the HashMap
using the containsKey()
method. The key is specified as the parameter, and the method returns true
if the key exists, and false
otherwise.
1boolean hasCharlie = scores.containsKey("Charlie");
Removing Key-Value Pairs
To remove a key-value pair from the HashMap
, you can use the remove()
method. The key is specified as the parameter, and the method removes the key-value pair if it exists.
1scores.remove("Alice");
Iterating Over Key-Value Pairs
You can iterate over the key-value pairs in the HashMap
using a for-each loop and the entrySet()
method. The entrySet()
method returns a Set
object containing the key-value pairs as Map.Entry
objects. Each Map.Entry
object contains the key and value.
1for (Map.Entry<String, Integer> entry : scores.entrySet()) {
2 String name = entry.getKey();
3 int score = entry.getValue();
4 System.out.println(name + ": " + score);
5}
xxxxxxxxxx
}
class Main {
public static void main(String[] args) {
// create a HashMap
HashMap<String, Integer> scores = new HashMap<>();
// add key-value pairs to the HashMap
scores.put("Alice", 85);
scores.put("Bob", 90);
scores.put("Charlie", 95);
// retrieve values from the HashMap
int aliceScore = scores.get("Alice");
System.out.println("Alice's score: " + aliceScore);
// update a value in the HashMap
scores.put("Bob", 92);
// check if a key exists in the HashMap
boolean hasCharlie = scores.containsKey("Charlie");
System.out.println("Charlie in HashMap: " + hasCharlie);
// remove a key-value pair from the HashMap
scores.remove("Alice");
// iterate over the key-value pairs in the HashMap
for (Map.Entry<String, Integer> entry : scores.entrySet()) {
String name = entry.getKey();
int score = entry.getValue();
System.out.println(name + ": " + score);