Tutorial

How To Use Maps in Java

Published on January 19, 2024
How To Use Maps in Java

The author selected Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

Introduction

A map in Java is a group of entries, each with two linked parts - a key and a value. In essence, Map is an interface from the java.util package. To use it, you have to choose one of its most popular implementations:

  • Hashmap is the fastest and most often used implementation. You will be using it throughout this tutorial.
  • LinkedHashMap is slower than Hashmap, but guarantees iteration in order of insertion. So you should use it if you want the map entries to appear in the order they were inserted when iterated.
  • ConcurrentMap is thread-safe and you should use it if you expect more than one thread to perform operations on your map.

Prerequisites

To follow this tutorial, you will need:

Creating Maps

When creating a map, you must first decide which map implementation you will use. As mentioned initially, the HashMap implementation is the fastest and most suitable for general use. That’s why you will use it in this tutorial.

To begin, you will create a map of the world’s capitals. Each entry in the capitals map will have a key with the country name and a value with the capital name. This is a good example because every country has a unique name and thus the keys cannot overlap. Also, each country has only one capital, so it will fit into the one available corresponding value. Both the key and the value will be alphanumeric, thus you will use String objects for them.

Info: To follow along with the example code in this tutorial, open the Java Shell tool on your local system by running the jshell command. Then you can copy, paste, or edit the examples by adding them after the jshell> prompt and pressing ENTER. To exit jshell, type /exit.

  1. Map<String, String> capitals = new HashMap<>();

The map declaration starts with defining the reference type - Map. Inside the diamond operator (<>) you declare that both keys and values are of type String. You could omit the latter but then you might get warnings when the code is executed. You also risk failures when inserting a key or a value of a type which cannot be casted.

When you execute the above statement you will get the following output in jshell:

Output
capitals ==> {}

This confirms that an empty map called capitals has been created.

Adding Map Entries

To specify a new map entry, you must define a key and value pair. Create the first one like this:

  1. capitals.put("France", "Lyon");

Using the put method on the capitals object you created a new entry with a key France and a value Lyon.

The output in jshell will be similar to:

Output
$2 ==> null

The temporary variable $2 can be disregarded here and throughout the rest of the tutorial. It points to null. Although not very intuitive, this means that there hasn’t been such a value for this key before.

You can re-use indefinitely the same key in maps. So, to correct the entry for France and make Paris the capital, you can run in jshell:

  1. capitals.put("France", "Paris");

This time the temporary variable will point to the old value for the France key:

Output
$3 ==> "Lyon"

Let’s add another capital, this time correct from the start:

  1. capitals.put("Germany", "Berlin");

You will see again only a confirmation that the previous value was null:

Output
$8 ==> null

Finally, to confirm that you have two entries in the capitals map, just type the name of the map in jshell:

  1. capitals

The output will confirm the two entries for France and Germany:

Output
capitals ==> {France=Paris, Germany=Berlin}

Removing Map Entries

To remove a map entry, you have to pass its key as an argument to the remove method. For example, to remove the entry for Germany from the capitals type in jshell:

  1. capitals.remove("Germany");

The following output will be produced:

Output
$6 ==> "Berlin"

This confirms that there has been an entry by the key Germany with value Berlin and it has been removed. If you run again the same remove statement with the same key for Germany, you will not get such an output. Instead, you will get a temporary variable pointing to null:

Output
$7 ==> null

Similarly to the behavior of the put method, these temporary variables come from the fact that the remove method returns the value of the removed key. Thus, when you remove an entry, you can optionally assign the result to a String like this:

String removedCapital = capitals.remove("France");

Then you can print this variable using System.out.println:

  1. System.out.println(removedCapital);

In jshell you will see printed the name of the removed capital:

Output
Paris

Finally, if you want to remove all the map entries, you can use the clear method without any arguments:

  1. capitals.clear();

After the above execution your capitals map will be empty. You will not see a confirmation after the command succeeds.

Using Additional Map Methods

The Map interface and its implementations provide very useful and powerful methods for interacting with a Map object. You have already used some of them such as add and remove but there are a few more worth mentioning.

get Method

The get method accepts as an argument a key and returns its corresponding value. For the example which follows, add again an entry in the capitals map since it may be empty by now.:

  1. capitals.put("Germany", "Berlin");

Then, get this entry and assign it to a String variable capitalOfGermany like this:

  1. String capitalOfGermany = capitals.get("Germany");

You will see a confirmation that the value of Berlin has been assigned to the variable:

Output
capitalOfGermany ==> "Berlin"

size Method

The size method gives the number of entries in a map. Its return type is an integer (int). To continue our examples, find out how many entries there are in the capitals map and assign the result to a numberOfCapitals variable:

  1. int numberOfCapitals = capitals.size();

If you have followed the examples thus far, there should be at least one entry in the map. Therefore numberOfCapitals will have a value of 1:

Output
numberOfCapitals ==> 1

toString Method

The method toString lists the map entries in a human-readable String format. As an example, you can invoke it on capitals to create a new String variable capitalAsString:

  1. String capitalAsString = capitals.toString();

This will result in a confirmation that the String value of {Germany=Berlin} has been assigned to capitalAsString:

Output
capitalAsString ==> "{Germany=Berlin}"

As an exercise, add more entries to the capitals map and invoke again the toString method to see how the String representation of the map changes.

keySet and values Methods

If you need only the keys or the values of a map you can obtain them with the keySet or values methods respectively. For example:

To get all the keys you can use keySet:

  1. capitals.keySet();

This prints a temporary variable pointing to the map keys, i.e. countries:

Output
$15 ==> [France, Germany]

To get the values you can use values:

  1. capitals.values();

This time the temporary variable will point to the map values, i.e. capitals:

Output
$14 ==> [Paris, Berlin]

containsKey and containsValue Methods

To find out whether a certain key or value is found in a map, you can use the methods containsKey and containsValue. Both methods return a boolean value. If there is a match, the value will be true. If not, a false result will be returned.

Here are a few examples:

  1. capitals.containsKey("Germany");

This prints a true because the key is found:

Output
$17 ==> true

To get a false result you can look for a key such as Spain or other country which is not found in the map:

  1. capitals.containsKey("Spain")

As expected, you will get a false result:

Output
$19 ==> false

Similarly, you can look for a value like this:

  1. capitals.containsValue("Paris");

Since Paris is found, you will get a true result:

Output
$20 ==> true

getOrDefault Method

This method is useful if you always want to return a default value, even if no key is found. For example, you can use getOrDefault to search for a non-existing key like Spain and define that Not specified should be returned if the key is not found:

  1. capitals.getOrDefault("Spain", "Not specified")

In jshell you will see Not specified because there is no key with value Spain:

Output
$20 ==> "Not specified"

equals Method

The equals method is another boolean method which returns true if two compared maps contain exactly the same mappings. If not, false is returned. To try it, create another map such as formerCapitals:

  1. Map<String, String> formerCapitals = new HashMap<>();

Put an entry for Italy and one of its former capitals Milan:

  1. formerCapitals.put("Italy", "Milan");

Now can compare the two maps capitals and formerCapitals like this:

  1. capitals.equals(formerCapitals)

As expected, you will see false returned because the two maps are different

Output
$27 ==> false

forEach Method

The Map interface also defines useful methods like forEach. The latter is used to iterate over all map entries and perform an action on each key and value. It’s enough to know that this is possible and that the Map interface has other interesting and advanced methods. However, you will need additional knowledge covered in future tutorials to use them.

Conclusion

In this tutorial, you learned how to work with Java maps, particularly the HashMap implementation. You created a map with countries and their capitals and added and removed entries. You also learned best practices and useful methods for working with maps in Java.

For more on Java, check out our How To Code in Java series.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


Tutorial Series: How To Code in Java

Java is a mature and well-designed programming language with a wide range of uses. One of its unique benefits is that it is cross-platform: once you create a Java program, you can run it on many operating systems, including servers (Linux/Unix), desktop (Windows, macOS, Linux), and mobile operating systems (Android, iOS).

About the authors
Default avatar
Toli

author


Default avatar

Developer Advocate

I’m a Developer Advocate at DigitalOcean with a passion for Serverless and Low-Code Solutions.


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more