HashMap

PHOTO EMBED

Sun Jun 09 2024 10:19:16 GMT+0000 (Coordinated Universal Time)

Saved by @login

import java.util.*;
import java.util.Map;

public class HashMapExample {
    public static void main(String[] args) {
        // Create a new HashMap instance
        Map<String, Integer> ageMap = new LinkedHashMap<>();

        // Add key-value pairs to the map
        ageMap.put("John", 30);
        ageMap.put("Alice", 25);
        ageMap.put("Bob", 35);
        ageMap.put("Eve", 28);

        // Access values using keys
        System.out.println("Age of John: " + ageMap.get("John"));
        System.out.println("Age of Alice: " + ageMap.get("Alice"));

        // Update the value associated with a key
        ageMap.put("John", 32);
        System.out.println("Updated age of John: " + ageMap.get("John"));

        // Check if a key exists in the map
        String name = "Bob";
        if (ageMap.containsKey(name)) {
            System.out.println(name + " exists in the map.");
        } else {
            System.out.println(name + " does not exist in the map.");
        }

        // Remove a key-value pair from the map
        ageMap.remove("Eve");
        System.out.println("Map after removing Eve: " + ageMap);

        // Iterate over the map entries
        System.out.println("Iterating over map entries:");
        for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }

        // Clear the map
        ageMap.clear();
        System.out.println("Map after clearing: " + ageMap);
    }
}
content_copyCOPY