Mark As Completed Discussion

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.

TEXT/X-JAVA
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.

TEXT/X-JAVA
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.

TEXT/X-JAVA
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.

TEXT/X-JAVA
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.

TEXT/X-JAVA
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.

TEXT/X-JAVA
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.

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