The author selected Free and Open Source Fund to receive a donation as part of the Write for DOnations program.
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.To follow this tutorial, you will need:
An environment in which you can execute Java programs to follow along with the examples. To set this up on your local machine, you will need the following:
Familiarity with Java and object-oriented programming, which you can find in our tutorial How To Write Your First Program in Java.
An understanding of Java data types is discussed in our tutorial Understanding Data Types in Java.
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
.
- 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
:
Outputcapitals ==> {}
This confirms that an empty map called capitals
has been created.
To specify a new map entry, you must define a key and value pair. Create the first one like this:
- 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
:
- 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:
- 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
:
- capitals
The output will confirm the two entries for France and Germany:
Outputcapitals ==> {France=Paris, Germany=Berlin}
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
:
- 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
:
- System.out.println(removedCapital);
In jshell
you will see printed the name of the removed capital:
OutputParis
Finally, if you want to remove all the map entries, you can use the clear
method without any arguments:
- capitals.clear();
After the above execution your capitals
map will be empty. You will not see a confirmation after the command succeeds.
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
MethodThe 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.:
- capitals.put("Germany", "Berlin");
Then, get this entry and assign it to a String
variable capitalOfGermany
like this:
- String capitalOfGermany = capitals.get("Germany");
You will see a confirmation that the value of Berlin has been assigned to the variable:
OutputcapitalOfGermany ==> "Berlin"
size
MethodThe 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:
- 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:
OutputnumberOfCapitals ==> 1
toString
MethodThe 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
:
- String capitalAsString = capitals.toString();
This will result in a confirmation that the String
value of {Germany=Berlin}
has been assigned to capitalAsString
:
OutputcapitalAsString ==> "{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
MethodsIf 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
:
- 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
:
- capitals.values();
This time the temporary variable will point to the map values, i.e. capitals:
Output$14 ==> [Paris, Berlin]
containsKey
and containsValue
MethodsTo 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:
- 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:
- capitals.containsKey("Spain")
As expected, you will get a false
result:
Output$19 ==> false
Similarly, you can look for a value like this:
- capitals.containsValue("Paris");
Since Paris is found, you will get a true
result:
Output$20 ==> true
getOrDefault
MethodThis 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:
- 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
MethodThe 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
:
- Map<String, String> formerCapitals = new HashMap<>();
Put an entry for Italy and one of its former capitals Milan:
- formerCapitals.put("Italy", "Milan");
Now can compare the two maps capitals
and formerCapitals
like this:
- capitals.equals(formerCapitals)
As expected, you will see false
returned because the two maps are different
Output$27 ==> false
forEach
MethodThe 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.
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.
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).
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!