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
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024