Java Map Interface: An Introductory Guide

Athena Ozanich
Athena Ozanich

Published:

What is a Java map, and why does it matter? Well, a Java map is a tool developers use to find their coffee in the morning —ok, I joke. But seriously, Java maps are handy when coding any kind of software, which will be the subject of this post.

Young woman studying the subject of Java Maps and how she can use them to improve her software development.

This post will cover all of the basic level information you need to know about Java maps. You will learn why and how they can benefit your software. You will learn the mechanics of the Java map, methods that belong to the map interface, and classes that implement and extend from it. Finally, you will see some examples of the above in code format.

Let’s jump right in.

Download Now: An Introduction to Java & JavaScript

What Are Java Maps?

Java maps are used for many different functions and operations, but in short, they are a way to keep track of information in the form of key-value pairs. In Java, a map can consist of virtually any number of key-value pairs, but the keys must always be unique — non-repeating.

This is useful for tracking purchase numbers with the respective buyer, just as a simple example. This would allow a company to quickly and easily locate a specific purchase for a return if needed. Maps are so helpful that Java offers two different interfaces for interacting with a map, Map and Sorted Map. Furthermore, there are three map classes in Java: TreeMap, HashMap, and LinkedHashMap.

However, this is where things tend to get a little dicey; what exactly does the hierarchy look like for these different maps? So let’s take this one step at a time. In Java, you will often hear of terms like extends and implements. For the sake of those who may not know what those terms mean — it still confuses me sometimes — let's think of it a little differently.

Java Map Hierarchy

What does it mean when someone says the SortedMap extends Map? Well, it means that SortedMap is an extension of the Map interface. This is just a fancy way of saying it utilizes all the features of the Map interface, plus some additional feature(s). In this case, the SortedMap is that it also provides Key sorting, which the Map interface does not.

Likewise, when someone says x implements y — in this case, TreeMap implements SortedMap — it means that the TreeMap does its own thing but through use of the SortedMap interface.

Much simpler when you think of it like that. With that out of the way you can check out the image below for a visual representation of how these Java interfaces and objects work and what their hierarchy looks like behind the scenes.

Image Source

The Arrows may seem confusing, but they are simply there to indicate the object they are implementing or extending. The arrow points to the source by which the class or interface is influenced.

Each of these classes and interfaces behaves differently, and each has its own time to shine. Next, let's look at the Map Interface a little closer and see how it works.

The Java Map Interface

The Java Map Interface is unique because it does not allow for traversing; this is why the related classes were created to provide additional functionality. To traverse a Map object in Java, you must first convert it to a different data type, such as a Java set. This process opens up a new way of interacting with the data. However, it also changes the data type, which is not always desirable.

This is where the classes come in; let's look at those next.

  • HashMap: HashMap is the implementation of Map, but it doesn't maintain any order.
  • LinkedHashMap: LinkedHashMap is the implementation of Map. It inherits the HashMap class. It maintains insertion order.
  • TreeMap: TreeMap is the implementation of Map and SortedMap. It maintains ascending order.

As you can see, this creates much more dynamic Maps for various uses. Without these classes, the functionality of the Map would be very limited and, likely, largely unused. You might be asking yourself, ok, but how do I know which one I’m using? Well, that‘s all in the syntax. The syntax of declaring a Map object includes the declaration of the class you wish to use. Let’s dig a little deeper and see what that syntax looks like next.

Java Map Interface Syntax

The syntax for declaring a Map object is where things start to clear up and make a little more sense, it starts with declaring the data type using the keyword — Map in this case. Then you need to specify the data types for the keys and values, then you wrap it all up by declaring the new class object you wish to create using the new keyword.

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

It’s literally that easy, the above line of code creates a new Map object of the HashMap class. The process is the same for any of the aforementioned classes as well. Once you have the object made you need to be able to interact with it, this requires some methods that will allow you to to manipulate the data.

Next let’s look at some of the most common methods you will find yourself using with the Map objects you create.

Java Map Methods

There are a lot of methods available to the Java Map Interface, and all of them provide additional ways to interact with the map objects you might encounter. The complete list of methods is vast and covering all of them isn’t necessary as you might not encounter many of them often if at all. Regardless knowing the most common methods will get you out of a bind and back on track quickly. The following methods are typically the most common ones used in software development.

  • clear(): This method is used to clear and remove all of the elements or mappings from a specified Map collection.
  • containsKey(Object): This method is used to check whether a particular key is being mapped into the Map or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
  • containsValue(Object): This method is used to check whether a particular value is being mapped by a single or more than one key in the Map. It takes the value as a parameter and returns True if that value is found in the map.
  • entrySet(): This method is used to create a set out of the same elements contained in the map. It basically returns a set view of the map, or we can create a new set and store the map elements into them.
  • equals(Object): This method is used to check for equality between two maps. It verifies whether the elements of a map passed as a parameter are equal to the elements of this map or not.
  • get(Object): This method is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
  • hashCode(): This method is used to generate a hashCode for the given map containing keys and values.
  • isEmpty(): This method is used to check if a map has any key and value pair entries. If no mapping exists, then this returns true.
  • keySet(): This method is used to return a Set view of the keys in this map. The map backs the set, so changes to the map are reflected in the set, and vice-versa.
  • put(Object, Object): This method is used to associate the specified value with the specified key in this map.
  • putAll(Map): This method is used to copy all of the mappings from the specified map to this map.
  • remove(Object): This method is used to remove the mapping for a key from this map if it is present in the map.
  • size(): This method is used to return the number of key/value pairs available in the map.
  • values(): This method is used to create a collection out of the map's values. It returns a Collection view of the values in the HashMap.
  • getOrDefault(Object key, V defaultValue): Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
  • putIfAbsent(K key, V value): If the specified key is not already associated with a value (or is mapped to null), it associates it with the given value and returns null; otherwise returns the current value.

Here are some code examples of a few different Java Map object declarations.

Java Map Examples

Declaring Java Map Objects looks relatively similar across the board; however, there are some differences, so it is essential to know how each type of map is handled. In this section, you will see a few code block declarations for the different types of maps.

Create a Map in Java

// Importing required classes import java.util.*; // Main class public class GFG { // Main driver method public static void main(String[] args){ // Creating an empty HashMap Map map = new HashMap<>(); // Inserting entries in the Map // using put() method map.put("Dennis", 33); map.put("Charlie", 30); map.put("Frank", 45); // Iterating over Map for (Map.Entry e : map.entrySet()){ // Printing key-value pairs System.out.println(e.getKey() + " " + e.getValue()); } } }

This process in this example is the same for the other Java Map objects. The only thing that changes is the order in which you might get the pairs back. LinkedHashMaps preserve the order that they were added; the example below shows how that works.

// Importing required classes import java.util.*; // Main class public class GFG { // Main driver method public static void main(String[] args){ // Creating an empty HashMap Map map = new LinkedHashMap<>(); // Inserting entries in the Map // using put() method map.put("Dennis", 33); map.put("Charlie", 30); map.put("Frank", 45); // Iterating over Map for (Map.Entry e : map.entrySet()){ // Printing key-value pairs System.out.println(e.getKey() + " " + e.getValue()); } } }

The output above would return the entries in the same order they were added, as shown below.

Dennis 33 Charlie 30 Frank 45

And finally to drive home the points covered here you can check out the video below to learn more about Java Maps with coding examples.

Next Steps for Using Java Maps Interface

All other map classes will return the entries in random unspecified order. There is a lot to learn when it comes to the Java Map Interface, but with this information, you are ready to start to get started. By putting Java Maps to work and using the methods above, you can create some robust code that will drastically improve your software development.

java

Topics: Java

Related Articles

We're committed to your privacy. HubSpot uses the information you provide to us to contact you about our relevant content, products, and services. You may unsubscribe from these communications at any time. For more information, check out our Privacy Policy.

Learn more about the differences between and uses of these popular programming languages.