0
0
JavaConceptBeginner · 3 min read

What is Map in Java: Explanation and Example

In Java, a Map is a collection that stores data as key-value pairs, where each key is unique and maps to a specific value. It allows fast lookup, insertion, and deletion of values based on their keys.
⚙️

How It Works

Think of a Map like a real-life dictionary where you look up a word (the key) to find its meaning (the value). Each key in the map is unique, so you cannot have two entries with the same key. When you want to find a value, you just provide the key, and the map quickly returns the associated value.

Under the hood, Java provides different types of maps like HashMap and TreeMap. A HashMap uses a technique called hashing to store and find keys very fast, similar to how a library index helps you find a book quickly. A TreeMap keeps keys in a sorted order, like an alphabetically arranged phone book.

💻

Example

This example shows how to create a HashMap, add key-value pairs, and retrieve a value by its key.

java
import java.util.HashMap;
import java.util.Map;

public class MapExample {
    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("Age of Bob: " + ages.get("Bob"));
    }
}
Output
Age of Bob: 25
🎯

When to Use

Use a Map when you need to associate unique keys with values and quickly find, add, or remove data based on those keys. For example, you can use a map to store user IDs and their profiles, product codes and prices, or country names and their capitals.

Maps are especially useful when you want to avoid searching through a list to find an item. Instead, you directly access the value using its key, saving time and making your program faster.

Key Points

  • Map stores data as key-value pairs.
  • Keys are unique; values can be duplicated.
  • Common implementations include HashMap and TreeMap.
  • Maps provide fast access to values by keys.
  • Useful for lookups, caching, and indexing data.

Key Takeaways

A Map stores unique keys linked to values for fast data access.
HashMap is the most common Map implementation for quick lookups.
Use Maps when you need to find data by keys without searching.
Keys must be unique, but values can repeat in a Map.
Maps are ideal for dictionaries, caches, and indexing tasks.