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
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.
Written by Neil Coffey. Copyright © Javamex UK 2012. All rights reserved. If you have any feedback on the Java collections tutorials in this section or about the content of this site in general, please leave a message on the Javamex forum.