Java Code Example: simple HashMap example

This code creates a HashMap with keys of type String and values of type Integer, and adds three key-value pairs to it: “apple” maps to 1, “banana” maps to 2, and “orange” maps to 3. It then prints out the contents of the HashMap, checks if “apple” is present in the HashMap, removes the key-value pair with key “banana” from the HashMap, and prints out the contents of the HashMap again. Finally, it iterates over the keys and values in the HashMap and prints each key-value pair.

import java.util.HashMap;

public class HashMapExample {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<>();

        // Adding elements to the HashMap
        map.put("apple", 1);
        map.put("banana", 2);
        map.put("orange", 3);

        // Printing the HashMap
        System.out.println(map);

        // Checking if a key is present in the HashMap
        if (map.containsKey("apple")) {
            System.out.println("The HashMap contains apple.");
        } else {
            System.out.println("The HashMap does not contain apple.");
        }

        // Removing a key-value pair from the HashMap
        map.remove("banana");

        // Printing the HashMap after removing a key-value pair
        System.out.println(map);

        // Iterating over the keys and values in the HashMap
        for (String key : map.keySet()) {
            System.out.println(key + " => " + map.get(key));
        }
    }
}