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 a given IP address, what is the host name?
- for a given request to our web server, what is the last result we returned?
- for a given parameter, what is the corresponding value?
- for a given session ID, what is the user name?
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:
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:
- efficient access: maps generally store their data in structures that provide much
more efficient lookups and scalable performance than if we were to cycle through an array, for example;
- convenient API: aside from the effiency motive, methods such as get() and set() are less
cumbersome than having to iterate through data manually;
- integration with other structures/data manipulation methods: as part of the
Java Collections Framework, Java maps integrate easily with other data structures such
as lists, sets, and with the Java lambdas and Streams API.
One of the key ways in which map implementations achieve their efficiency is through the technique that gives HashMap its name:
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.