Java Map Fundamentals

In this article, we’ll cover how the map data structure works, how to use it in Java, and explore what’s new with maps in Java 9.

What is a Map?

A map is a data structure that’s designed for fast lookups. Data is stored in key-value pairs with every key being unique. Each key maps to a value hence the name. These pairs are called map entries.

In the JDK, java.util.Map is an interface that includes method signatures for insertion, removal, and retrieval.

Collections Framework

The Map interface is implemented by a number of classes in the Collections Framework. Each class offers different functionality and thread safety. The most common implementation is the HashMap so we’ll be using this for most of our examples.

Map is the only collection that doesn’t extend or implement the Collection interface. It doesn’t fit the same contract since it needs to work with pairs instead of single values.

Create a Map

The keys and values of a map can be any reference type. We can’t use primitive types because of a restriction around the way generics were designed.

A HashMap allows one null key and multiple null values. It doesn’t preserve the order of the elements and doesn’t guarantee the order will remain the same over time.

Let’s create a HashMap with Integer keys and String values:

Since all maps implement the Map interface, the following methods will work for any of the map implementations illustrated above.

Add to a Map

The put() method allows us to insert entries into our map. It requires two parameters: a key and its value.

Now, let’s populate our map with id’s and names:

Here’s what our map looks like now:

1 -> Petyr Baelish 
2 -> Sansa Stark
3 -> Jon Snow
4 -> Jamie Lannister

Sometimes we may want to add multiple entries in bulk or combine two maps. There’s a method that handles this called putAll(). It copies the entry references from another map in order to populate ours.

Duplicate Keys

We mentioned before that duplicate keys aren’t allowed in maps.

Let’s see what happens when we try to insert a key that already exists:

The method doesn’t complain, but notice how the new value overwrote the previous one:

1 -> Petyr Baelish 
2 -> Sansa Stark
3 -> Jon Snow
4 -> Daenerys Targaryen

The put method returns the previous value if we care to use it. If there was no previous value, it returns null.

To check whether a key already exists, we use the containsKey() boolean method:

Similarly, the containsValue() method checks for existence of a value:

Retrieve from a Map

The get() method accepts a key and returns the value associated with that key or null if there is no value.

Remove from a Map

The remove() method accepts a key so it can find the entry to remove. It returns the value associated with the removed entry or null if there is no value.

1 -> Petyr Baelish 
2 -> Sansa Stark
4 -> Daenerys Targaryen

If we want to empty the map, we can call clear(). This is a void method so it does not return anything.

Map Size

The size() method returns number of entries in our map.

The isEmpty() method returns a boolean indicating if the map is empty or not.

Collection Views

The Map interface provides Collection view methods which allow us to view our map in terms of a collection type. These views provide the only mechanism for us to iterate over a map.

  • keySet() — returns a Set of keys from the map
  • values() — returns a Collection of values from the map
  • entrySet() — returns a Set of Map.Entry objects which represent the key-value pairs in the map

It’s important to remember that views are backed by our map. This means any changes we make to the view update the underlying map and vice versa.

The collection views support removal of entries but not insertion.

keySet()

The keySet() method returns a Set view of the keys contained in our map:

values()

The values() method returns a Collection of the values contained in our map:

Why does it return a Collection instead of a Set? Because the values of a map aren’t guaranteed to be unique so a Set wouldn’t work.

entrySet()

The entrySet() method is used to get a Set view of the entries in our map. The Set will contain Map.Entry objects. A Map.Entry object is simply a key-value pair. We can call getKey() or getValue() on this object.

The most common usage of the entrySet is for looping which we’ll cover in the next section.

Iterating over a Map

There are many ways of iterating over a map. Let’s go over some common approaches.

Keep in mind that loops will throw a NullPointerException if we try to iterate over a map that is null.

Using foreach and Map.Entry

This is the most common method and is preferable in most cases. We get access to both keys and values in the loop.

Using Java 8 Lambda expression

Sort a Map by Key

HashMap does not preserve any order in its entries. Here’s an example that illustrates this point:

The above code outputs the contents of the map in seemingly random order:

key: 20, value: Beth 
key: 40, value: Lucy
key: 10, value: Amir
key: 30, value: Arnie

If we use a TreeMap, it will automatically sort the entries by key. Let’s convert our HashMap to a TreeMap and print the contents:

The output is now sorted by key:

key: 10, value: Amir 
key: 20, value: Beth
key: 30, value: Arnie
key: 40, value: Lucy

Sort a Map by Value

This one is a little trickier and requires us to write a method.

  • On line 3, we create a list named entries which contains Map.Entry objects from the map we passed into the method.
  • On line 5, we use the Collections.sort() and implement a Comparator using entry.getValue() so it knows how to compare the entries.
  • At this point, our list containing the entry objects is sorted by value. Now, we need to get it back into a map.
  • On line 12, we create a LinkedHashMap which is a map implementation that preserves the insertion order of its entries.
  • On lines 14–16, we iterate over our list and populate the new map.

Let’s see this method in action:

The output is now sorted by value:

key: 1, value: Amir 
key: 3, value: Arnie
key: 2, value: Beth
key: 4, value: Lucy

New in Java 9

One of the enhancements Oracle has made in Java 9 is adding syntactic sugar for creating immutable maps. By immutable, we mean it cannot change — no adding or removing entries is permitted.

Here’s how we create an immutable map in Java 8:

This looks confusing and awkward. Those double braces are particularly unusual.

Java 9 introduces a static factory method named Map.of() to make this a bit cleaner.

Here’s the new way to do it in Java 9:

A word of caution here — the new factory method doesn’t make it obvious that it creates an immutable map. In our example, we named the variable immutableMap so it would be clear to other developers.

Also, keep in mind that the map still has methods for adding and removing entries. These will throw UnsupportedOperationException if invoked:

Originally published at www.codebyamir.com on June 28, 2017.