Java Map Interface

The Java Map Interface

A Map is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

The Map interface is a member of the Java Collections Framework but it does not extend the Collection interface. It represents a different type of collection structure based on key-value pairs.


Key Characteristics of a Map


Common Map Methods

Method Description
V put(K key, V value) Associates the specified value with the specified key in this map.
V get(Object key) Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
V remove(Object key) Removes the mapping for a key from this map if it is present.
boolean containsKey(Object key) Returns true if this map contains a mapping for the specified key.
boolean containsValue(Object value) Returns true if this map maps one or more keys to the specified value.
int size() Returns the number of key-value mappings in this map.
Set<K> keySet() Returns a Set view of the keys contained in this map.
Collection<V> values() Returns a Collection view of the values contained in this map.
Set<Map.Entry<K, V>> entrySet() Returns a Set view of the mappings contained in this map.

Map Implementations

The three most common implementations are:

  1. HashMap: The most widely used Map implementation. It is backed by a hash table. It offers the best performance (O(1) for get and put) but makes no guarantees about order.
  2. TreeMap: This implementation stores keys in a sorted order. Its performance is slower (O(log n)) than HashMap.
  3. LinkedHashMap: This implementation maintains the insertion order of keys. It provides performance nearly as good as HashMap.

Creating a Map

Here is an example of how to use a HashMap to store student IDs and names.

Creating and Using a Map

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

public class Main { public static void main(String[] args) { // Declare as a Map, instantiate as a HashMap Map<Integer, String> studentMap = new HashMap<>(); // Add key-value pairs studentMap.put(101, "Alice"); studentMap.put(102, "Bob"); studentMap.put(103, "Charlie"); System.out.println("Map of students: " + studentMap); // Get a value by its key String studentName = studentMap.get(102); System.out.println("Student with ID 102 is: " + studentName); // Remove an entry studentMap.remove(103); System.out.println("Map after removing student 103: " + studentMap); // Loop through the keys System.out.println("--- Looping through keys ---"); for (Integer id : studentMap.keySet()) { System.out.println("ID: " + id + ", Name: " + studentMap.get(id)); } } }