How do I use the HashMap class?

This example demonstrate you how to use the HashMap class to store values in a key-value structure. In this example we store a map of error codes with their corresponding description. To store a value into the map we use the put(key, value) method and to get it back we use the get(key) method. And we can also iterate the map using the available key sets of the map.

package org.kodejava.util;

import java.util.HashMap;
import java.util.Map;

public class HashMapDemo {
    public static void main(String[] args) {
        Map<String, String> errors = new HashMap<>();

        // mapping some data in the map
        errors.put("404", "Resource not found");
        errors.put("403", "Access forbidden");
        errors.put("500", "General server error");

        // reading data from the map
        String errorDescription = errors.get("404");
        System.out.println("Error 404: " + errorDescription);

        // Iterating the map by the keys
        for (String key : errors.keySet()) {
            System.out.println("Error " + key + ": " + errors.get(key));
        }
    }
}

The result of the code snippet above:

Error 404: Resource not found
Error 500: General server error
Error 403: Access forbidden
Error 404: Resource not found
Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.