top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Map In Java

In the realm of Java programming, the Map interface provides a powerful tool for handling key-value pairs and implementing these concepts. In this article, we will delve into the world of Map in Java, exploring its interface, hierarchy, useful methods, and various examples. So let's embark on this journey of unraveling the essence of data manipulation in Java.

Overview

The Map interface does not allow duplicate keys and each one can map to at most one value. Key and value pairs are used to store data in Java's Map interface, which is part of the java.util package. It prohibits the use of duplicate keys. It's common to think of Java's map interface as a subtype of the Collections interface. The map in Java acts differently from the Collection interface, so that is untrue.

You may access the latter via a map interface since it associates special keys with distinct values. Three sets are kept in sync by the Java Map interface: keys, values, and key/values maps (mapping). Each of these can be accessed separately.

Java Map Interface

A key and value pair, or map, is a collection of values based on a given key. An entry is a pair of keys and values. Each key on a map is different. If you need to search, update, or remove elements based on a key, a map can be helpful.

Java Map Hierarchy

Map and SortedMap are the two interfaces from which you can implement maps in Java. The Map interface is expanded by the SortedMap interface. Three classes are available to implement maps. HashMap, LinkedHashMap, and TreeMap are the names of these three classes.  The Java Map hierarchy is provided below:

The HashMap class that implements the Map interface is extended by the LinkedHashMap class. The SortedMap interface, which extends the Map interface, is implemented by the TreeMap class. The hierarchy of the Map interface in Java is represented by the flowchart diagram shown below.

Useful map methods in Java

Let's explore some of the useful methods provided by the Map interface:

  • get(): The Java map get () method retrieves the value associated with a given key. It returns null if the key is not present in the map.

  • put(): The put() method inserts a key-value pair into the map. If the key already exists, the associated value is replaced.

  • remove(): This method removes the key-value pair associated with a given key from the map.

  • containsKey(): The containsKey() method checks if a specified key exists in the map.

  • containsValue(): This method determines whether a particular value is present in the map.

Why and when to use Maps

It is ideal to use the Map interface with Java objects like dictionaries that hold data in a key: value pair because it produces a mapping between key: value pairs. Maps are also your best bet when you need to obtain, modify, or extract values using keys. Some common scenarios where maps are beneficial include:

  • Storing user preferences: Maps can be used to store user preferences, where each one can be associated with a specific key.

  • Caching: Maps are often employed for caching purposes, where frequently accessed data can be stored and retrieved quickly.

  • Counting occurrences: Maps can help in counting occurrences of elements in a dataset, where the elements serve as keys and their counts as values.

How to Create Map Objects?

Java does not permit the creation of objects via an interface, and the same is true for maps. To build objects of this type, you require classes that implement the map interface. The three classes that implement the map interface can all be used to build map objects. Using the HashMap class, here's an illustration of how to make a map object:

Map obj = new HashMap();

Map.Entry Interface

The map.Entry in Java is nested within the Map interface and represents a key-value pair. It provides methods to access and modify the key and value associated with an entry in a map. The entrySet() method of the Map interface returns a set of Map.Entry objects, allowing you to iterate over the key-value pairs in a map.

What Are the Classes That Implement Map Interface in Java?

Java provides several classes that implement the Map interface. Some of the commonly used ones include HashMap, LinkedHashMap, TreeMap, and Hashtable. Each of these classes has its own characteristics and is suitable for different use cases.

  • HashMap: As mentioned earlier, HashMap is an implementation of the Map interface that provides fast retrieval and insertion operations.

  • LinkedHashMap: LinkedHashMap in Java maintains the insertion order of elements, making it suitable for scenarios where the order of insertion needs to be preserved.

  • TreeMap: TreeMap is a sorted implementation of the Map interface, where the elements are sorted based on their keys.

  • Hashtable: Hashtable is a synchronized implementation of the Map interface. It ensures thread safety but comes with a performance overhead.

Methods of Map.Entry interface 

The Map.Entry interface provides several methods to interact with the key-value pairs stored in a map. Some of the commonly used ones include getKey(), getValue(), and setValue(). These allow you to access and modify the key and value associated with a specific entry.

See the table below for more methods of Map.Entry interface:

  1. K getKey()- It is used to obtain a key.

  2. V getValue()- It is used to obtain value.

  3. int hashCode()- It is used to obtain hashCode.

  4. V setValue(V value)- It is used to replace the value corresponding to this entry with the specified value.

  5. Boolean equals(Object o)- It is used to compare the specified object with the other existing objects.

  6. static <K extends Comparable<? super K>,V> Comparator<Map.Entry<K,V>> comparingByKey()- It returns a comparator that compares the objects in natural order on key.

  7. static <K,V> Comparator<Map.Entry<K,V>> comparingByKey(Comparator<? super K> cmp)- It returns a comparator that compares the objects by key using the given Comparator.

  8. static <K,V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue()- It returns a comparator that compares the objects in natural order on value.

  9. static <K,V> Comparator<Map.Entry<K,V>> comparingByValue(Comparator<? super V> cmp)- It returns a comparator that compares the objects by value using the given Comparator.

Java Map Example: Non-Generic (Old Style)

import java.util.*;  
public class MapExample1 {  
public static void main(String[] args) {  
    Map map=new HashMap();  
    //Adding elements to map  
    map.put(6,"Lista");  
    map.put(7,"Danica");  
    map.put(8,"Sterlyn");  
    map.put(9,"Dero");  
    //Traversing Map  
    Set set=map.entrySet();
    Iterator itr=set.iterator();  
    while(itr.hasNext()){  
        //Converting to Map.Entry to get key and value separately 
        Map.Entry entry=(Map.Entry)itr.next();  
        System.out.println(entry.getKey()+" "+entry.getValue());  
    }  
}  
}  

Output: 

This code adds elements to the map, traverses through it using an iterator, and prints the key-value pairs in the map.

Java Map Example: Generic (New Style)

Output: 

This code creates a generic Java Map using a HashMap, adds key-value pairs to the map, and prints them in no specific order using a for-each loop.

Java Map Example: comparingByKey()

import java.util.*;  
class MapExample3{  
 public static void main(String args[]){  
Map<Integer,String> map=new HashMap<Integer,String>();     
      map.put(700,"Venny");    
      map.put(701,"Rael");    
      map.put(702,"Rahul");   
      //Returns a Set view of the mappings  
      map.entrySet()  
      //Returns a sequential Stream with this collection as its source  
      .stream()  
      //Sorted according to the provided Comparator  
      .sorted(Map.Entry.comparingByKey())  
      //Performs an action for each element of this stream  
      .forEach(System.out::println);  
 }  
} 

Output: 

This code creates a Java Map using a HashMap, adds key-value pairs to the map, and prints them in ascending order of the keys using the comparingByKey() method from the Map.Entry interface.

Java Map Example: comparingByKey() in Descending Order

import java.util.*;  
class MapExample4{  
 public static void main(String args[]){  
Map<Integer,String> map=new HashMap<Integer,String>();
      map.put(700,"Akoch");    
      map.put(701,"Venny");    
      map.put(702,"Rachel");    
      //Returns a Set view of the mappings contained in this map    
      map.entrySet()  
      //Returns a sequential Stream with this collection as its source  
      .stream()  
      //Sorted according to the provided Comparator  
      .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))  
      //Performs an action for each element of this stream  
      .forEach(System.out::println);  
 }  
} 

Output: 

This code creates a Java Map using a HashMap, adds key-value pairs to the map, and prints them in descending order of the keys using the comparingByKey() method from the Map.Entry interface with the Comparator.reverseOrder() comparator.

Java Map Example: comparingByValue()

Output: 

Java Map Example: comparingByValue() in Descending Order

Output:

This code creates a Java Map, adds key-value pairs, and prints them in descending order of the values.

Characteristics of a Map Interface

The Map interface has several characteristics that make it a versatile tool for data manipulation:

  • Keys are unique: Each key in a map is unique, and no two keys can be the same.

  • Efficient retrieval: The Map interface provides efficient retrieval of values based on their associated keys.

  • Dynamic size: Maps can grow or shrink dynamically as elements are added or removed.

  • Key-value association: Maps allow you to associate a value with each key, providing a convenient way to organize data.

Different Operations That Are Performed With Maps in Java

With the Map interface, you can perform various operations on the map:

  • Adding elements: You can add new key-value pairs to a map using the put() method.

  • Removing elements: The remove() method allows you to remove a key-value pair based on its key.

  • Changing elements: To update the value associated with a key, you can simply use the put() method with the existing key.

  • Iterating through the map: You can iterate over the key-value pairs in a map using the enhanced for loop or the entrySet() method.

Java map computeifabsent

The computeIfAbsent method in the Java Map interface is a powerful tool for handling key-value pairs. It allows you to compute a new value for a given key if it is not already present in the map. 

This method takes a key and a mapping function as parameters. If the key exists in the map, the method returns its associated value. If it is not found, the mapping function is invoked to compute a new value, which is then added to the map and returned. This method is incredibly useful for lazy initialization and dynamic value computation.

Map in Javascript

In JavaScript, a map is a built-in data structure that allows you to store key-value pairs. It is similar to an object but provides additional methods and functionalities specifically designed for working with key-value data.

Here's how you can create and use a map in JavaScript:

Output:

The code creates a JavaScript Map object, adds key-value pairs, performs operations like retrieval, checking existence, and iteration, and outputs the results.

Java stream map example

Output:

The code uses Java Stream to convert a list of names to uppercase and collect them into a new list.

Conclusion

In this article, we have explored the essence of the Map interface in Java and detailed its interface, hierarchy, and various implementations. We have also seen how to use the Map interface to store, retrieve, and manipulate data in a key-value format. By understanding the power and flexibility of the Map interface, you can effectively manage and manipulate data in your Java programs.

FAQs

1. What are the 5 methods of map interface?

The five commonly used methods of the Map interface in Java are put(), get(), remove(), containsKey(), and containsValue().

2. What is HashMap in Java?

HashMap is one of the implementations of the Map interface in Java.

3. What is the map in Java?

In Java, a map is an interface that represents a collection of key-value pairs, allowing efficient retrieval, insertion, and removal of elements based on their keys.

Leave a Reply

Your email address will not be published. Required fields are marked *