How do I use the HashMap class?

This examples demonstrate you how to use the HashMap class to map some values. In this example we map the error codes with their description. To store some data into the map we use the put() method and to get it back use the get() method. And we can also interate the map using the available key sets of the map.

package org.kodejava.example.lang;

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

public class HashMapDemo {
    public static void main(String[] args) {
        Map 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 errorDesc = (String) errors.get("404");
        System.out.println("Error 404: " + errorDesc);

        // iterating the map by it's keys
        Iterator iterator = errors.keySet().iterator();
        while (iterator.hasNext()) {
            String key = (String);
            System.out.println("Error " + key + " means " + errors.get(key));


Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply