Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (4 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How to Implement Map Interface in Java?

Last updated on Jun 17,2021 14.8K Views

12 / 22 Blog from Java Collections

One of the most interesting topics in Java is the Map interface which represents a mapping between a key and a value. It is often misunderstood to be a subtype of Collection interface in Java. This article on Java Map Interface will help you understand and master how a map works in Java.

Listed below are the topics covered in this article:

Java Map Interface

A Map in Java is an object that maps keys to values and is designed for the faster lookups. Data is stored in key-value pairs and every key is unique.  Each key maps to a value hence the name map.  These key-value pairs are called map entries.

Maps in Java - Java Map Interface - Edureka

In the JDKjava.util.Map is an interface that includes method signatures for insertion, removal, and retrieval of elements based on a key. With such methods, it’s a perfect tool to use for key-value association mapping such as dictionaries.

Characteristics of Map Interface

  • The Map interface is not a true subtype of Collection interface, therefore, its characteristics and behaviors are different from the rest of the collection types.
  • It provides three collection views – set of keys, set of key-value mappings and collection of values.
  • Map cannot contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null value (HashMap and LinkedHashMap) but some does not (TreeMap).
  • The Map interface doesn’t guarantee the order of mappings, however, it depends on the implementation. For instance, HashMap doesn’t guarantee the order of mappings but TreeMap does.
  • AbstractMap class provides a skeletal implementation of the Java Map interface and most of the Map concrete classes extend AbstractMap class and implement required methods.

Now that you have an idea of what Map interface in Java is, let’s go ahead and check out the hierarchy of Java Map.

Java Map Hierarchy

There are two interfaces that implement the Map in java: Map and SortedMap. And popular implementation classes of Map in Java are HashMap, TreeMap, and LinkedHashMap. The hierarchy of Java Map is given below:

Map Interface - Java Map Interface - Edureka

Before we check out the three implementation classes of the Java Map Interface mentioned above, here are some common methods that you can come across when working with the Map.

Methods in Java Map Interface

Methods

Description

public put(Object key, Object value)This method inserts an entry in the map
public void putAll(Map map)This method inserts the specified map in this map
public Object remove(Object key)It is used to delete an entry for the specified key
public Set keySet()It returns the Set view containing all the keys
public Set entrySet()It returns the Set view containing all the keys and values
void clear()It is used to reset the map
public void putIfAbsent(K key, V value)It inserts the specified value with the specified key in the map only if it is not already specified
public Object get(Object key)It returns the value for the specified key
public boolean containsKey(Object key)
It is used to search the specified key from this map

Implementations of Map

There are several classes that implement the Java Map but three major and general-purpose implementations are HashMap, TreeMap, and LinkedHashMap. Let’s see the characteristics and behaviors of each implementation with an example program.

HashMap Class

The most common class that implements the Java Map interface is the HashMap. It is a hash table based implementation of the Map interface. It implements all of the Map operations and allows null values and one null key. Also, this class does not maintain any order among its elements. Here’s an example program demonstrating the HashMap class.

package MyPackage;

import java.util.*; 

class HashMapExample {
	 
    public static void main(String[] args) {
	        Map< String, Integer> courses = new HashMap< String,Integer>();
	 
	        // Add some courses.
	        courses.put("Java Courses", new Integer(6));
	        courses.put("Cloud Courses", new Integer(7));
	        courses.put("Programming Courses", new Integer(5));
	        courses.put("Data Science Courses", new Integer(2));
	 
	        System.out.println("Total courses: " + courses.size());    
	        
	        Set< Map.Entry< String,Integer> > st = courses.entrySet();    
	        
	        for (Map.Entry< String,Integer> me :st) 
	        { 
	            System.out.print(me.getKey()+":"); 
	            System.out.println(me.getValue()); 
	        } 
	        System.out.println();
	 
	        String searchKey = "Java Courses";
	        if (courses.containsKey(searchKey))
	            System.out.println("Found total " + courses.get(searchKey) + " " + searchKey);
	 
	    }
	}

Output

Total courses: 4
Cloud Courses:7
Programming Courses:5
Data Science Courses:2
Java Courses:6

Found total 6 Java Courses

 

In the above program, I have used a lot of methods mention in the table. Firstly, the put() method inserts 4 entries into the map, and the size() method in the next step displays the size of the map (total key-value pairs). After that, in the next step, the entrySet() method returns all the key-value pairs. The program also shows how to make use of get() method to search for a value using the associated key.

Let’s move on to the next class that implements the Java Map Interface – TreeMap.

TreeMap Class

This implementation uses the Red-Black tree as the underlying data structure. A TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at creation time. This implementation doesn’t allow nulls but maintains order on its elements. Here’s an example program demonstrating the TreeMap class.

package MyPackage;

import java.util.*; 

class TreeMapEx{
	 
    public static void main(String[] args) {
	        Map< String, Integer> courses = new TreeMap< String,Integer>();
	 
	        // Add some courses.
	        courses.put("Java Courses", new Integer(3));
	        courses.put("AWS Courses", new Integer(7));
	        courses.put("Programming Courses", new Integer(8));
	        courses.put("Data Science Courses", new Integer(2));
	 
	        System.out.println("Total courses: " + courses.size());    
	        
	        Set< Map.Entry< String,Integer> > st = courses.entrySet(); 
	        for (Map.Entry< String,Integer> me :st) 
	        { 
	            System.out.print(me.getKey()+":"); 
	            System.out.println(me.getValue()); 
	        } 
	        System.out.println();
    }
}

Output

Total courses: 4
AWS Courses:7
Data Science Courses:2
Java Courses:3
Programming Courses:8

In the output, the elements of the map are printed in a strict lexicographic order, which does not appear in the previous examples of HashMap. The next class that we are going to discuss are LinkedHashMap.

LinkedHashMap Class

As the name indicates this implementation of Java Map interface uses a hash table and a linked list as the underlying data structures. Thus the order of a LinkedHashMap is predictable, with insertion-order as the default order. Also, allows nulls like in HashMap. Here’s an example program demonstrating the TreeMap class.

package MyPackage;

import java.util.*; 
	  
	public class LinkedHashMapExample 
	{ 
	    public static void main(String a[]) 
	    { 
	        LinkedHashMap<String, Integer> courses = 
	                       new LinkedHashMap<String, Integer>(); 
	        courses.put("Java Courses", new Integer(3));
	        courses.put("Cloud Courses", new Integer(7));
	        courses.put("Programming Courses", new Integer(8));
	        courses.put("Data Science Courses", new Integer(2));
	 
	  
	        // It prints the elements in same order  
	        // as they were inserted     
	        System.out.println(courses); 
	        System.out.println("Total courses: " + courses.size());  
	        System.out.println("Contains key 'Hadoop'? "+  courses.containsKey("Hadoop"));
	  
	        System.out.println("Getting value for key 'Programming Courses': " + courses.get("Programming Courses"));
	        System.out.println("Is map empty? " + courses.isEmpty());
	        
	        System.out.println("delete element 'Cloud Courses': " +  courses.remove("Cloud Courses")); 
	                           
	        System.out.println(courses); 
	    } 
	} 

Output

{Java Courses=3, Cloud Courses=7, Programming Courses=8, Data Science Courses=2}
Total courses: 4
Contains key 'Hadoop'? false
Getting value for key 'Programming Courses': 8
Is map empty? false
delete element 'Cloud Courses': 7
{Java Courses=3, Programming Courses=8, Data Science Courses=2}

The example program is pretty simple to understand. I have used some basic methods to demonstrate the functioning of LinkeHashMap in Java. Like I said earlier there apart from these three there are a lot of other classes that implement Java Map interface.

This brings us to the end of this ‘Java Map Interface’ article. I have covered one of the interesting topics of Java, which is Map interface in Java. 

Make sure you practice as much as possible and revert your experience.  

Check out the Java Certification Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. 

Got a question for us? Please mention it in the comments section of this ‘java Map interface’ article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 28th September,2024

28th September

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Implement Map Interface in Java?

edureka.co