![]() | Session 12 | ![]() |
Map
A map (in Python - dictionary) is an object that stores associations between keys and values, or key/value pairs. A map enables fast retrieval, deletion, and updating of the pair through the key. A map stores the values along with the keys. The keys are like indexes. In List, the indexes are integers. In Map, the keys can be any objects. A map cannot contain duplicate keys. Each key maps to one value. A key and its corresponding value form an entry stored in a map.
One of the most useful map classes of the Map interface is HashMap.
In the following example, a telephone book is simulated:
Map<String, Integer> telephoneBook = new HashMap<>();
telephoneBook.put("Peeter Peet", 5562356);
telephoneBook.put("Mari Maasikas", 53438956);
System.out.println("Mari's number is " + telephoneBook.get("Mari Maasikas"));
Note: a map has two generic types in the angle brackets: one for the key (String) and one for its value (Integer).
Also note that get returns the null value if the map contains no mapping for the key.
![]() | Session 12 | ![]() |

