Map in Java


Java Java MapViews 1969

Map interface in Java

In Java, Map is an interface that is part of the Collection framework and stores data in the form of key-value pairs. It is not a subtype of Collection interface and hence has its own special feature. We can retrieve the value based on the corresponding key. An entry represents individual key-value pairs.

Features of Java Map

  • Contains only unique keys and does not allow storing duplicate keys.
  • Every key maps to only a single value
  • The order of data depends on the map implementation.
  • There are 5 classes that implement the Map interface: HashMap, EnumMap, LinkedHashMap, WeakHashMap, and TreeMap.
  • There are 3 interfaces that extend the Map interface: SortedMap, NavigableMap, and ConcurrentMap.

Java Map hierarchy

Map in Java

Methods of Java Map

MethodDescriptionParameter
void clear()Removes all the mappings in this map which means map will be empty
Boolean containsKey(Object key)Returns true if there is a mapping value for the specified keykey - the key for which we need to retrieve the value
Boolean containsValue(Object value)Returns true if there is mapping of key for the specified valuevalue - the value for which specified key is mapped
Set<Entry> entrySet()Returns a set view of the mapping of the map
Boolean equals(Object o)Returns true if the object has the same mapping of the mapo - the object to be compared
Integer get(Object key)Returns the value of the specified key in the map. It returns null if there is no mappingkey - the key for which value mapping has to be retrieved
Integer getOrDefault(Object key, Integer defaultvalue)Returns the value of the specified key if mapped, else returns the defaultvalue if there is no mappingkey - the key for which we value has to be returned
defaultvalue - the default value to be returned when there is no mapping
int hashCode()Returns the hashcode value of the map
Boolean isEmpty()Returns true is the map does not have any key-value pairs
Set keySet()Returns the set view of the keys present in the map
Integer put(String key, int value)Associates the key with value. If the key is already present, it replaces the old value with new valuekey - key for mapping
value - value for the specified key
void putAll(Map m)Associates all key - value mappings of m to the current mapm - the copies of the mapping to be added to the current map
Integer putIfAbsent(String key,Integer value)Associates the value if already not mapped to the key else returns the current valuekey - key for mapping
value - value to be associated
Integer remove(Object key)Removes the mapping for the specified key in the mapkey - the key in the map for which mapping has to be removed
Boolean remove(Object key, Object value)Removes the entry of the specified key only if it is mapped with the specified valuekey - key in map
value - value mapped to the key
Integer replace(String key, Integer value)Replaces the value of the specified key with the value only if it currently mapped with some valuekey - key in map
value - value to be replaced
Boolean replace(String key, integer oldvalue, Integer newvalue)Replaces the entry of the specified key with new value only if it already mapped with the specified oldvaluekey - key in the map
oldvalue - oldvalue mapped to key
newvalue - newvalue to be mapped to the key
int size()Returns the size of the map
String toString()Returns a string representation of the map
Collection values()Returns a collection view of values present in the map

Classes that implement the Map interface

A map is an interface in Java and hence we cannot create an instance directly. Hence there are different classes that can implement a Map that is discussed below.

HashMap

HashMap uses a hashtable data structure to store the data in the form of a key-value pair and does not maintain any order. It allows storing one null key and multiple null values.

import java.util.Map;
import java.util.HashMap;
public class AddMapElements {

  public static void main(String[] args) {
    Map<Integer,String> m = new HashMap<Integer,String>();
    m.put(1, "Chennai");
    m.put(2,"Bangalore");
    m.put(3, "Delhi");
    
    System.out.println(m);
  }

}
{1=Chennai, 2=Bangalore, 3=Delhi}

LinkedHashMap

LinkedHashMap implements a LinkedList data structure and hence maintains insertion order. It extends the HashMap class. It uses a double LinkedList to traverse or iterate through all the nodes.

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapDemo {

  public static void main(String[] args) {
    Map<Integer, String> m = new LinkedHashMap<Integer, String>();
    m.put(1, "Chennai");
    m.put(2, "Bangalore");
    m.put(3, "Delhi");
    
    System.out.println(m);
  }

}
{1=Chennai, 2=Bangalore, 3=Delhi}

EnumMap

EnumMap is a special implementation of the Map interface that is used for the Enumeration or enum data type. It maintains the natural sorting order based on the keys. Each key in an EnumMap is an instance of each enum data.

import java.util.EnumMap;

enum Speed {
  LOW, MEDIUM, HIGH
}
public class EnumMapDemo {

  public static void main(String[] args) {
    EnumMap<Speed, String> e = new EnumMap<Speed, String>(Speed.class);
    e.put(Speed.LOW, "Low");
    e.put(Speed.MEDIUM, "Medium");
    e.put(Speed.HIGH, "High");
    
    System.out.println("Size of EnumMap: " + e.size());
    System.out.println("Values in EnumMap" + e);

  }

}
Size of EnumMap: 3
Values in EnumMap{LOW=Low, MEDIUM=Medium, HIGH=High}

WeakHashMap

A WeakHashMap is similar to a HashMap but has only weak references to its keys. This means if it no longer has a strong reference to the object of the key then the Java Memory manager will remove that entry from the Map.

TreeMap

TreeMap uses a tree-based data structure to store the data in the form of key-value pairs. By default, it maintains ascending order and does not allow null keys and values.

import java.util.Map;
import java.util.TreeMap;

public class TreeMapDemo {

  public static void main(String[] args) {
    Map<Integer, String> m = new TreeMap<Integer, String>();
    m.put(1, "Sharma");
    m.put(2, "Sabarish");
    m.put(3, "Rakesh");
    
    System.out.println(m);

  }

}
{1=Sharma, 2=Sabarish, 3=Rakesh}

Interfaces that extend the Map interface

The Map interface has several subinterfaces that extend it. Below is the list of subinterfaces.

SortedMap

The SortedMap maintains a natural sorting order based on the keys. The TreeMap class implements the SortedMap interface. We can also sort the elements based on the comparator. It does not allow strong null keys or values.

NavigableMap

The NavigableMap is an extension of the SortedMap that provides special functions to navigate through the SortedMap. The special methods are lowerKey, floorKey, ceilingKey, and higherKey. It also allows creating a submap using the headMap and tailMap methods.

ConcurrentMap

ConcurrentMap is a special map interface that handles concurrent access without affecting the consistency of the entries in the Map. The ConcurrentHashMap and ConcurrentSkipListMap implements this interface.

Map.Entry interface

Entry is another subinterface of Map which we use to retrieve keys and values. We can access this using the Map.Entry name. This interface provides methods to get and set key and values, For eg: getKey(), getValue(), setValue(), etc.

There are also other methods that return the collection view in ascending and descending order using the ComparingByKey() and comparingByValue() method.

Example: ComparingByKey method

Below is an example of using the ComparingByKey method of the Map.Entry interface to sort in ascending and descending order based on the keys.

import java.util.*;

public class ComparingByKeyDemo {

  public static void main(String[] args) {
    Map<Integer, String> m = new HashMap<Integer, String>();
    m.put(1, "Anu");
    m.put(2, "Ravi");
    m.put(3, "Chaitanya");
    
    //Print in ascending order
    System.out.println("Ascending order");
    m.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByKey())
    .forEach(System.out:: println);
    
    //Print in descending order
    System.out.println("Descending order");
    m.entrySet()
    .stream()
    .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
    .forEach(System.out:: println);

  }

}
Ascending order
1=Anu
2=Ravi
3=Chaitanya
Descending order
3=Chaitanya
2=Ravi
1=Anu

Example: CompareByValue method

Below is an example of the CompareByValue method of the Map.Entry interface to sort in ascending and descending order based on the values.

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

public class ComparingByValueDemo {

  public static void main(String[] args) {
      Map<Integer, String> m = new HashMap<Integer, String>();
      m.put(1, "Anu");
      m.put(2, "Ravi");
      m.put(3, "Chaitanya");
      
      //Print in ascending order
      System.out.println("Ascending order");
      m.entrySet()
      .stream()
      .sorted(Map.Entry.comparingByValue())
      .forEach(System.out:: println);
      
      //Print in descending order
      System.out.println("Descending order");
      m.entrySet()
      .stream()
      .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
      .forEach(System.out:: println);
      

  }

}
Ascending order
1=Anu
3=Chaitanya
2=Ravi
Descending order
2=Ravi
3=Chaitanya
1=Anu

 

Reference

Translate »