Java•HashMaps
Java HashMap: Key-Value Mapping and Collections
Learn HashMap operations: put, get, getOrDefault, containsKey, and iterating over entry sets.
Syntax
HashMap<String, Integer> map = new HashMap<>();
map.put("key", 100);
int val = map.get("key");
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| HashMap<K, V> | Hash Table | Map implementation based on hash table with O(1) average lookup. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Java locally:
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
HashMap<String, Integer> portMap = new HashMap<>();
// Inserting mappings
portMap.put("HTTP", 80);
portMap.put("HTTPS", 443);
portMap.put("SSH", 22);
// Safe lookup with getOrDefault
int redisPort = portMap.getOrDefault("REDIS", 6379);
System.out.println("HTTPS Port: " + portMap.get("HTTPS"));
System.out.println("REDIS Port: " + redisPort + " (fallback)");
System.out.println("\nPort Registry:");
for (Map.Entry<String, Integer> entry : portMap.entrySet()) {
System.out.println(" " + entry.getKey() + " -> " + entry.getValue());
}
}
}Expected Output:
HTTPS Port: 443 REDIS Port: 6379 (fallback) Port Registry: SSH -> 22 HTTP -> 80 HTTPS -> 443
How It Works: Step-by-Step
- Lines 5-11: Populates HashMap with protocol names and port numbers.
- Lines 14-16: Uses getOrDefault to avoid null when key is missing.
- Lines 19-21: Iterates through entrySet() to print keys and values.
Key Concepts
- HashMap does not guarantee any specific order of keys.
- getOrDefault(key, default) avoids NullPointerException on missing keys.
- LinkedHashMap preserves insertion order; TreeMap maintains sorted order.
Common Mistake: Unboxing null return value into a primitive int
map.get("missing") returns null; assigning to primitive int throws NullPointerException.
❌ Incorrect
int port = portMap.get("UNKNOWN"); // Throws NullPointerException!✅ Correct
int port = portMap.getOrDefault("UNKNOWN", 8080); // SafeRelated Java Tutorials & Compiler
Java ArrayList and Arrays: Dynamic Collections vs Fixed Arrays
Master fixed-size arrays and dynamic java.util.ArrayList with add, get, and remove.
Java HashSet: Deduplication and Unique Sets
Store unique collections of elements with java.util.HashSet and set operations.
Java String Methods, StringBuilder, and Immutability
Master String methods (split, substring, replace) and mutable StringBuilder for performance.
Java Online Compiler
Open in Compilra IDE
Run and test Java on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.