HashMap & Key-Value Pairs
HashMap stores data as key-value pairs, allowing you to look up values by their keys in O(1) time. It's perfect for dictionaries, caches, frequency counts, and configurations. This is a foundational concept in enterprise application development that professional developers rely on daily. The explanations below are written to be beginner-friendly while covering the depth and nuance that comes from real-world Java experience. Take your time with each section and practice the examples
40 min•By Priygop Team•Last updated: Feb 2026
HashMap Operations
Example
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo {
public static void main(String[] args) {
// Creating a HashMap
HashMap<String, Integer> ages = new HashMap<>();
// Adding key-value pairs
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 28);
ages.put("Diana", 22);
System.out.println("Ages: " + ages);
// Getting values
System.out.println("Alice's age: " + ages.get("Alice"));
System.out.println("Contains Bob? " + ages.containsKey("Bob"));
// Default value if key not found
System.out.println("Eve's age: " + ages.getOrDefault("Eve", -1));
// Updating
ages.put("Alice", 26); // Overwrites old value
System.out.println("Alice updated: " + ages.get("Alice"));
// Removing
ages.remove("Diana");
System.out.println("After remove: " + ages);
// Iterating
System.out.println("\nAll entries:");
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(" " + entry.getKey() + " → " + entry.getValue());
}
// Word frequency counter
String text = "java is great and java is fun and java is powerful";
String[] words = text.split(" ");
HashMap<String, Integer> freq = new HashMap<>();
for (String word : words) {
freq.put(word, freq.getOrDefault(word, 0) + 1);
}
System.out.println("\nWord frequencies: " + freq);
}
}Try It Yourself: Contact Book
Try It Yourself: Contact BookJava
Java Editor
✓ ValidTab = 2 spaces
Java|36 lines|1272 chars|✓ Valid syntax
UTF-8