foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Java
  • Understand key-value pair storage
  • Learn HashMap creation and operations
  • Master put, get, remove methods

Working with Maps (HashMap)

Maps store key-value pairs, making them perfect for scenarios where you need to associate one piece of data with another. HashMap is the most commonly used Map implementation in Java.

What is a HashMap?

A HashMap is a collection that stores data in key-value pairs. Each key maps to exactly one value, and keys must be unique (but values can be duplicated).

Creating a HashMap

// Empty HashMap
HashMap<String, Integer> ages = new HashMap<>();

// HashMap with initial capacity
HashMap<String, String> capitals = new HashMap<>(50);

// From another map
Map<String, Integer> map1 = new HashMap<>();
HashMap<String, Integer> map2 = new HashMap<>(map1);

Common HashMap Operations

Adding and Updating

HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);    // Add new entry
scores.put("Bob", 87);
scores.put("Alice", 98);    // Update existing - replaces 95 with 98

Retrieving Values

int score = scores.get("Alice");           // Returns 98
int defaultScore = scores.getOrDefault("Charlie", 0);  // Returns 0 (default)

Checking Keys and Values

boolean hasAlice = scores.containsKey("Alice");     // true
boolean has100 = scores.containsValue(100);         // false

Removing Entries

scores.remove("Bob");      // Remove by key
scores.clear();            // Remove all entries

Getting Size

int size = scores.size();
boolean empty = scores.isEmpty();

Iterating Through HashMap

Iterating Over Keys

for (String name : scores.keySet()) {
    System.out.println(name);
}

Iterating Over Values

for (Integer score : scores.values()) {
    System.out.println(score);
}

Iterating Over Entries

for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

When to Use HashMap

Use HashMap when you need:

  • Fast lookups by key (O(1) average)
  • To associate keys with values
  • To check if a key exists quickly
  • No specific ordering required

Common use cases:

  • Storing user data (username → User object)
  • Caching results (input → computed result)
  • Counting occurrences (item → count)
  • Configuration settings (key → value)

Important Notes

  1. Keys must be unique - putting a new value with an existing key replaces the old value
  2. Keys can be null - but only one null key is allowed
  3. Values can be null - and duplicated
  4. No guaranteed order - iteration order is not predictable
  5. Not thread-safe - use ConcurrentHashMap for multi-threaded scenarios

HashMap gives you fast O(1) key-based access with flexible key-value storage. Perfect for lookups and associations.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service