Java

TOPIC 21 – JAVA COLLECTIONS III - MAPS

 

 

LESSON NOTE

 

 

INTRO

 

A map data structure pairs two pieces of data together.  The first is called the key and it is unique in the map.  The second is called the value and it is not necessarily unique. 

 

The type of the key and value objects is specified using generics. 

 

IMPLEMENTATIONS

 

Two commonly used implementations are HashMap and TreeMap.  We will not worry about how they differ.  You can research that on your own if you are interested. 

 

 

EXAMPLE CODE 1

Here is the code to create a HashMap structure that will have a String key and an Integer value.

 

    HashMap<String,Integer> hm = new HashMap<String,Integer>();

 

EXAMPLE CODE 2

 

Here is the code to create a TreeMap structure that will have a String key and a Point value.

 

    TreeMap<String,Point> tm = new TreeMap<String,Point>();

 

 

FUNCTIONALITY

 

Here are the most important methods for map structures:

 

  • put(key, value) – Adds a pair into the map.  If the key is already in the map, it overwrites the value.
  • remove(key) – Removes the pair with key.
  • get(key) – Returns the value that is associated with key.
  • containsKey(key) – Returns true if the key is in the map
  • containsValue(value) – Returns true if the value is in the map

 

 

EXAMPLE CODE

 

TreeMap<String,Integer> map = new TreeMap<String,Integer>();

map.put("Ironman", 4);

map.put("Black Widow", 10);

map.put("Captain America", 9);

          

String keyToCheck = "Black Widow";    //change this value

if (map.containsKey(keyToCheck) == true)

     System.out.println("Clearance level:" + map.get(keyToCheck));

else

     System.out.println("You are not in the system.");

 

 

RESULTING OUTPUT

 

Clearance level:10