Java:Java HashMap: Key-Value Mapping and Collections
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:

ParameterTypeDescription
HashMap<K, V>Hash TableMap implementation based on hash table with O(1) average lookup.

Ready-to-Run Code Example

Executable in Compilra

Run 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); // Safe

Related Java Tutorials & Compiler

Run and test Java on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Java Online Compiler