Java Collections: maps

A map is a frequently used type of data structure that allows mappings or associations to be set up between one set of objects and another. By association, we typically mean situations where we want to say "for a given X, what is the Y?". For example:

In some other languages (including Objective C and Swift), the map structure is referred to as a dictionary or associative array. But in Java, the term map is most commonly used and this term occurs in the names of various classes that implement them (e.g. HashMap).

Maps have a variety of uses such as caches, lookups and a variety of data organisation purposes. A whole host of routines would be inefficient and fiddly to write without them.

How to declare and use a map in Java

To use a map in Java, we use an instance of the Map interface. Provided it will only be accessed by a single thread, the most common type of Map is the HashMap. For example, we can declare a map that associates string keys with integer values as follows:

Map<String,Integer> params = new HashMap();

Perhaps this map represents some integer settings, for example. Now, we can set and get parameters from this map by using the get() and set() methods:

params.set("maxConnections", 20);
params.set("maxThreads", 10);
int maxConnections = params.get("maxConnections");
int maxThreads = params.get("maxThreads");

As alluded to above, the items that we associate from are referred to as keys. The items that we associate to (the integers in this case) are referred to simply as values.

Advantages of maps and HashMaps

Using a Java Map to map keys to values offers a number of advantages:

One of the key ways in which map implementations achieve their efficiency is through the technique that gives HashMap its name: hashing.

If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.

Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.