linked hashmap

PHOTO EMBED

Fri Jun 07 2024 13:58:10 GMT+0000 (Coordinated Universal Time)

Saved by @dbms

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapExample {
    public static void main(String[] args) {
        // Creating a LinkedHashMap to store names and ages
        LinkedHashMap<String, Integer> ageMap = new LinkedHashMap<>();

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

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

        // Updating a value using put() method
        ageMap.put("John", 32);
        System.out.println("Updated age of John: " + ageMap.get("John"));

        // Checking if a key exists
        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.");
        }

        // Removing an entry using remove() method
        ageMap.remove("Eve");
        System.out.println("Map after removing Eve: " + ageMap);

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

        // Checking size and emptiness
        System.out.println("Size of map: " + ageMap.size());
        System.out.println("Is map empty? " + ageMap.isEmpty());

        // Checking if map contains a key and value
        System.out.println("Contains key 'Bob': " + ageMap.containsKey("Bob"));
        System.out.println("Contains value 35: " + ageMap.containsValue(35));

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