Java ProgramsCollectionsHashMap Example

HashMap Example in Java

beginner·  Collections  ·  Map

Problem

A HashMap stores key-value pairs and gives near-instant lookup by key, without needing to scan through every entry the way a list search would.

Store a few people's ages in a HashMap keyed by name, then look one up and check whether another key exists.

Input
put("Alice", 30), put("Bob", 25), put("Charlie", 35)
Output
Bob's age: 25

Java Program

Java
import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { Map<String, Integer> ages = new HashMap<>(); ages.put("Alice", 30); ages.put("Bob", 25); ages.put("Charlie", 35); System.out.println("Bob's age: " + ages.get("Bob")); System.out.println("Contains Alice: " + ages.containsKey("Alice")); System.out.println("Contains Dave: " + ages.containsKey("Dave")); } }

Output

Bob's age: 25 Contains Alice: true Contains Dave: false

Core Logic

Storing each name-age pair with put() builds the map, and get()/containsKey() then query it directly by key instead of searching through it.

How It Works
  1. 1put("Alice", 30) and the two calls after it each store one key-value pair in the map.
  2. 2get("Bob") looks up the value stored under the key "Bob" and returns it directly.
  3. 3containsKey("Alice") checks whether that exact key exists in the map, returning a boolean rather than the value itself.
  4. 4containsKey("Dave") returns false, since no entry was ever stored under that key.
After the three put() calls, get("Bob") returns 25, and containsKey("Dave") correctly reports false.
💡

Key Point: get() on a missing key returns null rather than throwing — containsKey() is the safer check when a map might not have a given key at all.

Complexity
Time Complexity: O(1)Space Complexity: O(1)

Why: put(), get(), and containsKey() each hash the key directly to its bucket, giving average-case constant time; only a pathological hash collision pattern would push any single call toward O(n).

Key Concepts

HashMapput()get()containsKey()

Related Programs