Learn Java , Selenium

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", "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:

OperationExample
Add a key-value pairput("France", "Paris")
Get value by keyget("India") โ†’ Delhi
Check if key existscontainsKey("USA")
Remove a pairremove("Russia")
Get all keys or valueskeySet(), values()
Loop through key-value pairssee 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.

Scroll to Top