Map in Java

In Java, a Map is a data structure that stores key–value pairs. Each key is unique, but values can be duplicated. Maps are part of the Java Collections Framework, but they are not a subtype of Collection. Instead, they are their own interface in java.util.

Here’s a breakdown:


Map Interface

  • Found in java.util.
  • Represents a mapping from keys to values.
  • Commonly used implementations:
    • HashMap (unordered, most common)
    • LinkedHashMap (maintains insertion order)
    • TreeMap (sorted by natural order or a comparator)
    • Hashtable (legacy, synchronized)

Basic Methods

  • put(K key, V value) → adds or updates a mapping
  • get(Object key) → retrieves value by key
  • remove(Object key) → removes entry
  • containsKey(Object key) / containsValue(Object value)
  • size() → number of entries
  • keySet() → returns a set of keys
  • values() → returns a collection of values
  • entrySet() → returns a set of key-value pairs

Example: Using a HashMap

import java.util.*;

public class MapExample {
    public static void main(String[] args) {
        // Create a HashMap
        Map<String, Integer> map = new HashMap<>();

        // Add elements
        map.put("Alice", 25);
        map.put("Bob", 30);
        map.put("Charlie", 28);

        // Access elements
        System.out.println("Alice's age: " + map.get("Alice"));

        // Iterate through keys
        for (String key : map.keySet()) {
            System.out.println(key + " -> " + map.get(key));
        }

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

        // Check if key exists
        if (map.containsKey("Bob")) {
            System.out.println("Bob is in the map.");
        }
    }
}

Output:

Alice's age: 25
Alice -> 25
Bob -> 30
Charlie -> 28
Alice = 25
Bob = 30
Charlie = 28
Bob is in the map.

Leave a Reply