Using collections in Java: maps

In programming terms, a map is a set of associations between pairs of objects. It crops up extremely frequently in programming in all sorts of cases where we want to deal with cases of "for X, what is the Y"? For example:

Notice the third item here: a common use for a map is as a simple cache.

Creating and using a map

The syntax for creating a map is largely similar to lists and sets. But this time we need to specify the type of object we want to map from and the type to map to. Let's say we want to store an association of country codes with country names, in other words, String to String:

Map<String,String> countryNames = new HashMap<String,String>(200);

In this case, we use the common map implementation HashMap. As with the set, we supply an estimate of the number of mappings we expect to add, to help the map operate more efficiently1. To add an association to the map, we actually use a method called put():

countryNames.put("GB", "Great Britain");
countryNames.put("FR", "France");
countryNames.put("IT", "Italy");
countryNames.put("FW", "Far Far Away");

Then, to retrieve the country name for a particular code, we call:

String name = countryNames.get("IT");

Other things to note about Maps:

More on maps

For more advanced uses, it is useful to understand how maps work, in particular about the technique called hashing from which the HashMap and HashSet get their name.

All of our examples looked at putting "library" objects (that is, bogstandard Strings, Integers etc rather than classes of our creation) into the map. If the keys to our map are of a class or our creation, then in general we need to make our class compatible with hash maps by adding a hashCode() and equals() method.


1. Every time a collection becomes "full", it generally has to re-organise itself to accommodate the extra capacity needed. For example, an ArrayList needs to create a new, larger array. In the case of HashSet or HashMap, it turns out that this re-organisation is quite an "expensive" operation. So if we can anticipate roughly how many items will be added in the first place, we cut down on this expensive re-organisation.