793 Contributors: 36 Monday, July 17, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap



The java.util.Map interface represents a mapping between keys and their values. A map cannot contain duplicate keys; and each key can map to at most one value.

Since Map is an interface, then you need to instantiate a concrete implementation of that interface in order to use it; there are several Map implementations, and mostly used are the java.util.HashMap and java.util.TreeMap


A map is an object which store keys with an associated value for each key. A key and its value are sometimes called a key/value pair or an entry. Maps typically provide these features:

  • Data is stored into the map in key/value pairs.
  • The map may contain only one entry for a particular key. If a map contains an entry with a particular key, and you try to store a second entry with the same key, then the second entry will replace the first. In other words, this will change the value associated with the key.
  • Maps provide fast operations to test whether a key exists in the map, to fetch the value associated with a key, and to remove a key/value pair.

The most commonly used map implementation is HashMap. It works well with keys that are strings or numbers.

Plain maps such as HashMap are unordered. Iterating through key/value pairs may return individual entries in any order. If you need to iterate through map entries in a controlled fashion, you should look at the following:

  • Sorted maps such as TreeMap will iterate through keys in their natural order (or in an order that you can specify, by providing a Comparator). For example, a sorted map using numbers as keys would be expected to iterate through its entries in numeric order.

  • LinkedHashMap permits iterating through entries in the same order that they were inserted into the map, or by the order of most recently accessed.

Related Examples