HashMap is a collection that stores data as key-value pairs. With an array or list you look things up by index, but with a HashMap you look things up by key — handy for storing things like username to user role, product code to price, or country to capital city.
java
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> productPrices = new HashMap<String, Integer>();
productPrices.put("Keyboard", 50);
productPrices.put("Mouse", 25);
productPrices.put("Monitor", 200);
System.out.println(productPrices);
System.out.println("Mouse price: " + productPrices.get("Mouse"));
System.out.println("Has Keyboard: " + productPrices.containsKey("Keyboard"));
}
}HashMap<String, Integer> is a map that stores String keys and Integer values. You add data with put() and grab a value with get(key). containsKey() checks whether a key exists.
You should see
{Mouse=25, Keyboard=50, Monitor=200} Mouse price: 25 Has Keyboard: trueReal-World Use
HashMap is commonly used for things like user settings, product prices, API response mappings, translation dictionaries, and cache data.