Map in Java is an interface available in java.util package and it stores the data in key and value pairs. It does not allow duplicate keys. The map interface in Java is often misunderstood as being a subtype of the Collections interface. But that is not true, and hence, the Java map functions differently from the Collection interface.

Since it associates unique keys with values, you can access the latter using a map interface. The Java Map interface maintains three sets: keys, values, and key/values maps (mapping). It is possible to access all these sets individually.

What Is the Hierarchy of the Map Interface in Java?

You can implement maps in Java from two interfaces: Map and SortedMap. The SortedMap interface extends the Map interface. There are three classes to implement maps. These three classes are HashMap, LinkedHashMap, and TreeMap.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

The LinkedHashMap class extends HashMap that implements the Map interface. TreeMap class implements the SortedMap interface that extends the Map interface. The flowchart diagram depicted below represents the hierarchy of Map interface in Java.

MapInJava_1.

Different Operations That Are Performed With Maps in Java

The Map interface in Java can be used with the classes that implement it, to perform various operations. Some of the primary operations you can perform on the maps in Java are:

  • Adding elements
  • Removing elements
  • Changing elements
  • Iterating through the map

Let’s see an example for each operation. You will use the most commonly used HashMap to perform these operations.

Example: Adding Elements to a Map in Java

In the example below, you will use the put() method to add elements to a map. You will be using the HashMap class here to implement Java maps.

import java.util.*;

public class example{

    public static void main(String args[]){

        // Default initialization for map

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

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

        // Inserting the Elements

        m1.put(1, "Welcome");

        m1.put(2, "to");

        m1.put(3, "Simplilearn");

          m2.put(new Integer(1), "Welcome");

        m2.put(new Integer(2), "to");

        m2.put(new Integer(3), "Simplilearn");

        System.out.println(m1);

        System.out.println(m2);

    }

}

Output:

/MapInJava_2

Example: Removing Elements of a Map in Java

This time you will use the HashMap class and the remove() method to remove elements from a map in Java. You will pass the key value in the remove() method, eliminating the associated value.

import java.util.*;

public class example{

    public static void main(String args[]){

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

        // Adding Elements

        m1.put(new Integer(1), "Welcome");

        m1.put(new Integer(2), "to");

        m1.put(new Integer(3), "Simplilearn");

        m1.put(new Integer(4), "additional");

        m1.put(new Integer(5), "data");

        // Map before remove operations

        System.out.println(m1);

        m1.remove(new Integer(4));

        m1.remove(new Integer(5));

        // Map after remove operations

        System.out.println(m1);

    }

}

Output:

MapInJava_3

Learn From The Best Mentors in the Industry!

Automation Testing Masters ProgramExplore Program
Learn From The Best Mentors in the Industry!

Example: Changing Elements of a Map in Java

You can also change the elements already added to a Java map using the same put() method to add elements. The only change is that you will have to pass the key of the value you wish to change, this time.

import java.util.*;

public class example{

public static void main(String args[]){

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

// Adding elements

m1.put(new Integer(1), "Hi");

m1.put(new Integer(2), "to");

m1.put(new Integer(3), "Simplilearn");

System.out.println("Map before change " + m1);

m1.put(new Integer(1), "Welcome");

System.out.println("Map after change " + m1);

}

}

Output:

MapInJava_4.

Example: Iterating Through a Map in Java

In this example, you will traverse through a map in Java using the for-each loop and retrieve the values by the getValue() method. You can also use other ways to iterate through a map.

import java.util.*;

public class example{

public static void main(String args[]){

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

// Adding elements

m1.put(new Integer(1), "Welcome");

m1.put(new Integer(2), "to");

m1.put(new Integer(3), "Simplilearn");

for (Map.Entry mapElement : m1.entrySet()){

int key = (int)mapElement.getKey();

// Finding value

String val = (String)mapElement.getValue();

System.out.println(key + " : " + val);

}

}

}

Output:

MapInJava_5

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

When to Use the Map Interface in Java?

Since the Map interface creates a mapping between key: value pairs, it is best to use it with Java objects such as dictionaries that store data in a key: value pair. Maps are also the best option when you have to retrieve or alter the elements or extract values through keys. Standard examples of using a map in Java include:

  • Map of cities and their zip codes
  • Map of classes and students
  • Map of managers and employees
  • Map of errors and descriptions

How to Create Map Objects?

Java does not allow creating objects using an interface, and the same is true for maps too. Hence, you need classes that implement the map interface to create objects of this type. You can use any of the three classes that implement the map interface and use them for creating map objects. An example of creating a map object using the HashMap class is:

Map obj = new HashMap();

What Are the Classes That Implement Map Interface in Java?

The three primary classes that implement map in Java are:

  • HashMap
  • LinkedHashMap
  • TreeMap

Of these three, HashMap and LinkedHashMap classes allow null keys and values, but the TreeMap doesn’t. You will see examples of how to use all these classes to implement the map interface in Java in the latter section.

What Are the Methods of Map Interface in Java?

The map interface in Java provides various methods that help perform various operations on the map. The table depicted below describes some of the standard methods of the Java Map interface.

Method

Description

clear()

Clears and removes all the mappings

containsKey(Object)

Returns a boolean value depending on whether the specified key is mapped or not

containsValue(Object)

Returns a boolean value depending on whether the specified value is mapped or not

entrySet()

Creates a set and stores the map values into them

equals(Object)

Checks the equality between two maps

get(Object)

Returns the value mapped with the specified key or null if the key is not mapped

hashCode()

Generates a hashCode for the mentioned map

isEmpty()

Checks whether the map is empty

keySet()

Returns a set view of the mapped keys

put(Object, Object)

Adds a new key: value pair to the map

putAll(Map)

Copies all the mappings of the specified map into the new map

remove(Object)

Removes an element’s key mapping

size()

Returns the total number of key: value pairs in a map

value()

Creates a collection of the values of a map

Learn 15+ In-Demand Tools and Skills!

Automation Testing Masters ProgramExplore Program
Learn 15+ In-Demand Tools and Skills!

How to Implement Map Interface in Java?

As mentioned earlier, three primary classes implement the Map interface in Java. Let’s look at examples of implementing maps in Java using these three classes.

Example: Implementing Map in Java Using the HashMap Class

The HashMap class provides basic map implementation. It stores the elements in a key: value pair and uses a hashing technique to access the values through keys. Let’s create a map object with the help of the HashMap class and use various methods, in the following example:

import java.util.Map;

import java.util.HashMap;

public class example{

    public static void main(String[] args) {

        // Using HashMap to create a map

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

        // Adding elements

        num.put("One", 1);

        num.put("Two", 2);

        num.put("Three", 3);

        num.put("Four", 4);

        System.out.println("The Complete Map: " + num);

        // Accessing keys

        System.out.println("The Keys are: " + num.keySet());

        // Accessing values

        System.out.println("The Values are: " + num.values());

        // Accessing entries

        System.out.println("The Entries are: " + num.entrySet());

        // Removing elements

        int value = num.remove("Three");

        System.out.println("Value Removed: " + value);

    }

}

Output:

MapInJava_6

Example: Implementing Map in Java Using the LinkedHashMap Class

LinkedHashMap is similar to the HashMap class, only with an added functionality of maintaining order. The LinkedHashMap class can keep the order in which the elements were added, something that was missing in the HashMap class. Let’s look at the below example, where you can implement the map interface in Java using the LinkedHashMap class.

import java.util.*;

public class example{

    public static void main(String[] args){

        Map<String, Integer> mp1 = new LinkedHashMap<>();

        mp1.put("One", 1);

        mp1.put("Two", 2);

        mp1.put("Three", 3);

        mp1.put("Four", 4);

        for (Map.Entry<String, Integer> m : mp1.entrySet())

            System.out.println(m.getKey() + " " + m.getValue());

    }

}

Output:

MapInJava_7.

Example: Implementing Map Interface in Java Using the TreeMap Class

The Java TreeMap class implements Map Interface, NavigableMap, and Abstract Class. It differs from HashMap and LinkedHashMap because it provides an efficient way for sorting the map. You can sort the map either based on the keys or the constructor used. The code mentioned below uses the TreeMap class to implement a map in Java.

import java.util.Map;

import java.util.TreeMap;

public class example{

    public static void main(String[] args){

        // Using TreeMap class

        Map<String, Integer> val = new TreeMap<>();

        // Adding elements

        val.put("Second", 2);

        val.put("First", 1);

        val.put("Fourth", 4);

        val.put("Third", 3);

        System.out.println("Map using TreeMap: " + val);

        // Replacing elements

        val.replace("First", 11);

        val.replace("Third", 33);

        System.out.println("New Map: " + val);

        // Removing elements

        int remVal = val.remove("First");

        System.out.println("The Removed Value is: " + remVal);

    }

}

Output:

MapInJava_8

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Summing It Up

In this article, you learned everything about the Map interface in Java. You can use maps in Java whenever you want key-value mapping for accessing, changing and removing elements. Some everyday use cases include zip codes and cities mapping, error codes and descriptions mapping, and manager and employees mapping. 

Since you now have a clear understanding of the Map interface in Java, you need to practice it to get a firm grip on the interface’s practical usage. If you want to learn more about such interesting Java programming concepts, you can opt for Simplilearn’s Online Java Certification Course. The course covers all the basic and advanced concepts in Java, along with several hours of applied learning. This makes the course well-adept at helping you excel in Java development.

Do you have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on the same, ASAP!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 18 Dec, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449