Map Data Structure Tutorial

What are Map Data Structures?

The Map interface maps unique keys to values. The key is an object we use to retrieve a value.The Dictionary class defined a data structure for mapping keys to values. It was most useful when we wanted to access data with a specific key instead of an integer index. It’s an obsolete class now and the Map interface is used to obtain key/value storage features.

How & Why use Map Data Structures?

  • Store the value of a key in a Map object, to be retrieved later with it’s key.
  • When no items are found in the Map, several methods throw a NoSuchElementException.
  • ClassCastException is thrown when an object is incompatible with the map elements.
  • If null is not allowed in the map and we attempt to use a null object, a NullPointerException is thrown.
  • If we try to change a unmodifiable map, an UnsupportedOoperationException is thrown.

Code sample to show map functionality with HashMap class:

import java.util.*;
public class MapDemo {
   public static void main(String[] args) {
     Map map1 = new HashMap();
     map1.put("Monica", "5");
     map1.put("Walter", "8");
     System.out.println(" Map Elements ");
     System.out.print("t" + map1);

Code Output:

Map Elements
     {Walter=8, Isaac=7, Leola=3, Monica=5}


Leave a Reply