Maps

mapping

Maps are objects that hold values like ArrayLists, but their values can be indexed by objects instead of just integers.

The indexing set of objects is called the keys. The indexed set of objects is called the values.

Import from java.util.Map from the built-in Java library to use Map.

 

Creating Maps

Map map = new Map-type();

This creates a map of Map-type but used as Map. Map is an interface, so it cannot be instantiated, so another class must implement it, which we’ll call Map-type.

Here, map accepts both keys and values as Objects.

Map-type can be the following:

  • java.util.HashMap – Uses a special technique called hashing for faster indexing.
  • java.util.TreeMap – Automatically sorts elements in a given order as they are added.
  • And more, but these are the most used ones

Example:

Map map = new HashMap();

 

Constraining types

Map<KeyClass, ValueClass> map = new Map-type<KeyClass, ValueClass>();

This creates a map called map and limits the types of accepted keys to KeyClass, and the types of accepted values to ValueClass.

Example (try it):

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("price", 10);
map.put("quantity", 5);

 

Adding Associations

map.put(key, value)

This associates key to value in map.

Keys cannot be duplicate, but values can.

The associations are represented by the class Entry.

Example (try it):

map.put("key", "value");

 

Retrieving values

map.get(key)

This retrieves the value associated to key.

The returned value will be of the declared type for map’s values (if no type was declared, it returns an Object).

Example (try it):

System.out.println(map.get("key")); //prints "value"

 

READ  Values

Retrieving Keys

Use the method keySet() to retrieve a set of keys (of class Set).

Then you can call toArray() to retrieve the keys in an Array.

Example (try it):

Set set = map.keySet();
set.toArray();

 

Sorting by Keys

We do this several ways, each needing an implementation of the Comparator interface, like so:

class KeyComparator implements Comparator
{
    public int compare(Object a, Object b) 
    {
        if ((char) a > (char) b)
             return 1;
        else
             return -1;
    }
}

Then we can:

  • Use Treemap from the very beginning, which sorts entries as they are added (try it):
Map map = new TreeMap(new KeyComparator());
map.put('B', 3);          
map.put('A', 1);
map.put('C', 2);
  • Or make a TreeMap out of your unsorted map, which automatically sorts it (try it):
Map sortedmap = new TreeMap(new KeyComparator());
sortedmap.putAll(map);
  • Or sort a copy of the key list and extract each association by that sorted key order, like so (try it):
  //make map.
  Map map = new HashMap(); 
  map.put('B', 3);          
  map.put('A', 1);
  map.put('C', 2);
  
  //get keylist and sort it.
  List keylist = new ArrayList(map.keySet());
  Collections.sort(keylist, new KeyComparator());
  
  //extract associations and put in a new map.
  Map sortedmap = new HashMap();
  for (Object key: keylist)
       sortedmap.put(key, map.get(key));

 

Sorting by Values

One way to do this is putting your unsorted map into a new TreeMap, passing a comparator to it.

Difference from KeyComparator above is that this comparator must remember the map.

Example (try it):

import java.util.*;

class ValueComparator implements Comparator
{
     Map map;
     ValueComparator(Map map) 
     {
         this.map = map;
     }

     public int compare(Object a, Object b) 
     {
         if ((double) map.get(a) > (double) map.get(b)) 
             return 1;
         else 
             return -1;
     }
}

class Tester
{
     public static void main(String[] args) 
     {
         //make map.
         Map map = new HashMap(); 
         map.put("Beltre", .324);
         map.put("Martinez", .335);
         map.put("Alluve", .341);
         map.put("Brantley", .327);
         System.out.println("Unsorted: " + map);

         //put in a TreeMap.
         Comparator comparator = new ValueComparator(map); 
         Map sortedmap = new TreeMap(comparator);
         sortedmap.putAll(map);
         System.out.println("Sorted: " + sortedmap);
     }
}

A comparator is not truly needed if comparing strings, characters, or numbers, as Java knows how to sort them, but I used one for demonstration purposes.

Please like & share: