☕ Java

HashMap in Java

HashMap stores data as key-value pairs — like a dictionary or a phone book. You look up values by key in constant time O(1). It's one of the most powerful and commonly used data structures in real applications.

HashMap Basics — Key-Value Storage

Think of a HashMap like a real dictionary: words are keys, definitions are values. You look up the definition by searching for the word — not by scanning page by page. HashMap works the same way: instead of iterating through all elements, it uses a hash function to jump directly to where the value lives. This makes lookups near-instantaneous, even with millions of entries. Rules: • Keys must be unique (adding the same key again overwrites the value) • Values can repeat • Order is NOT guaranteed (use LinkedHashMap if you need insertion order, TreeMap for sorted order)
Java
import java.util.HashMap;

HashMap<String, Integer> wordCount = new HashMap<>();

// put — add or update key-value pairs
wordCount.put("java", 15);
wordCount.put("python", 8);
wordCount.put("javascript", 12);

// get — retrieve by key
System.out.println(wordCount.get("java"));      // 15
System.out.println(wordCount.get("ruby"));      // null — key doesn't exist

// getOrDefault — safer, avoids null
System.out.println(wordCount.getOrDefault("ruby", 0));  // 0

// check existence
System.out.println(wordCount.containsKey("python")); // true
System.out.println(wordCount.containsValue(8));      // true

// update — put replaces existing value
wordCount.put("python", 10);

// remove
wordCount.remove("javascript");

System.out.println(wordCount.size());  // 2

Iterating a HashMap

Java
HashMap<String, String> capitals = new HashMap<>();
capitals.put("India", "New Delhi");
capitals.put("UAE", "Abu Dhabi");
capitals.put("Japan", "Tokyo");

// Iterate over all key-value pairs (most common)
for (Map.Entry<String, String> entry : capitals.entrySet()) {
    System.out.println(entry.getKey() + " → " + entry.getValue());
}

// Keys only
for (String country : capitals.keySet()) {
    System.out.println(country);
}

// Values only
for (String capital : capitals.values()) {
    System.out.println(capital);
}

// Java 8 — forEach with lambda (clean and expressive)
capitals.forEach((country, capital) ->
    System.out.println("Capital of " + country + " is " + capital)
);