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 create a table with multiple header in iText 8? - March 16, 2024
- How do I add Image to a Table in iText 8? - March 11, 2024
- How do I downgrade Android SDK emulator version? - February 12, 2024