HashMap – In Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Program2 {
public static void main(String[] args) {
HashMap<String, String> country_capital =
new HashMap<String, String>();
country_capital.put("India", "Delhi");
country_capital.put("USA", "Washington DC");
country_capital.put("China", "Beijing");
country_capital.put("Russia", "Moscow");
System.out.println(country_capital);
}
}
๐งพ Output:
{China=Bejing, Russia=Moscow, USA=Washington DC, India=Delhi}
๐ก What is a HashMap?
A HashMap stores data in key-value pairs, and allows:
Fast lookup
No duplicate keys
One null key and multiple null values (if needed)
✅ Key Operations:
| Operation | Example |
|---|---|
| Add a key-value pair | put("France", "Paris") |
| Get value by key | get("India") → Delhi |
| Check if key exists | containsKey("USA") |
| Remove a pair | remove("Russia") |
| Get all keys or values | keySet(), values() |
| Loop through key-value pairs | see below ๐ |
๐ Looping through the HashMap:
๐ง When to Use a HashMap:
To store and quickly access data using a unique key.
Great for mapping IDs, usernames, names with details, etc.