Java HashMap CRUD Operations Example

1. Introduction

A HashMap in Java is a part of the Java Collections Framework and stores items in "key/value" pairs, where each key is unique. It provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. This blog post will cover basic CRUD (Create, Read, Update, Delete) operations in a HashMap.

2. Program Steps

1. Create a new HashMap.

2. Add key-value pairs to the HashMap (Create).

3. Retrieve a value from the HashMap using a key (Read).

4. Update the value associated with a specific key.

5. Remove a key-value pair from the HashMap (Delete).

3. Code Program

import java.util.HashMap;

public class HashMapCRUDExample {
    public static void main(String[] args) {
        // Step 1: Creating a new HashMap
        HashMap<Integer, String> map = new HashMap<>();

        // Step 2: Adding key-value pairs to the HashMap (Create)
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");
        System.out.println("Initial map: " + map);

        // Step 3: Retrieving a value from the HashMap (Read)
        String value = map.get(2); // Retrieve the value associated with key 2
        System.out.println("Value for key 2: " + value);

        // Step 4: Updating the value associated with a specific key
        map.put(2, "Blueberry"); // Update the value associated with key 2
        System.out.println("Map after updating key 2: " + map);

        // Step 5: Removing a key-value pair from the HashMap (Delete)
        map.remove(3); // Remove the key-value pair associated with key 3
        System.out.println("Map after removing key 3: " + map);
    }
}

Output:

Initial map: {1=Apple, 2=Banana, 3=Cherry}
Value for key 2: Banana
Map after updating key 2: {1=Apple, 2=Blueberry, 3=Cherry}
Map after removing key 3: {1=Apple, 2=Blueberry}

Explanation:

1. The program begins with creating a HashMap<Integer, String> named map. The Integer type is used for keys, and String for values.

2. Adding elements: The put() method adds key-value pairs to the map. If a key already exists, its value is replaced.

3. Reading elements: The get() method retrieves the value associated with a given key, demonstrating the map's read operation.

4. Updating elements: The same put() method is used to update the value for an existing key in the map. This showcases the map's update operation by changing the value for key 2 from "Banana" to "Blueberry".

5. Removing elements: The remove() method deletes a key-value pair based on the key, highlighting the map's delete operation by removing the entry for key 3.

6. The output shows the state of the map after each operation, demonstrating how to perform CRUD operations in a HashMap, a fundamental aspect of managing key-value pairs in Java applications.

Comments