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 country_capital = new HashMap();
country_capital.put("India", "Delhi");
country_capital.put("USA", "Washington DC");
country_capital.put("China", "Bejing");
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
:
ย
for (Map.Entry<String, String> entry : country_capital.entrySet()) {
System.out.println("Country: " + entry.getKey() + ", Capital: " + entry.getValue());
}
๐ง When to Use a HashMap
:
To store and quickly access data using a unique key.
Great for mapping IDs, usernames, names with details, etc.