Maps

2 minute read

Summary

map.containsKey(key) /* returns true if the key is in the map, false otherwise.*/
map.containsValue(value)
map.put(str, map.getOrDefault(str,0) + 1);//default to 0 and adding 1
map.put(key, value) /* stores a new key/value pair in the map. Overwrites any existing value for that key.*/
map.get(key);//get value from the key
Set set = map.keySet();//get all the keys

/* removes the key/value pair for this key if present. Does nothing if the key is not present. */
map.remove(key);// Concurrent Modification Exception in a Loop
itr.remove();// used to avoid concurrent modification exception using an Iterator

Filling up a map

Using getOrDefault

Notice the default value to 0

for (String str: list) {
    map.put(str, map.getOrDefault(str,0) + 1);
}
Using the if statements

Notice the Initialization with 1

for (int i = 0; i < longestEnglishWord.length(); i++) {
    Character key = longestEnglishWord.charAt(i);
    if (hashMap.containsKey(key)) {
        hashMap.put(key, hashMap.get(key) + 1);
    } else {
        hashMap.put(key, 1);//Initialize with 1
    }
}

Map Iterator using KeySet

Map<Integer, String> map = new HashMap<>();
//Iterator on all the keys
Iterator<Integer> itr = map.keySet().iterator();
while (itr.hasNext()){
    int key    = itr.next();
    String value  = map.get(key);
}

Map Iterator using EntrySet

Map<Integer, String> map = new HashMap<>();
Iterator<Map.Entry<Integer,String>> itr = map.entrySet().iterator()
while (itr.hasNext()){
    int key   = itr.getKey();
    String value = itr.value();
}

for (Map.Entry<Integer, String> entry : map.entrySet()){
    int key   = entry.getKey();
    String value = entry.getValue();
}

Removing the element

Iterator<Integer> itr = key.iterator();
while(itr.hasNext()) {
    int tempKey = itr.next();
    if(map.get(tempKey)%2 != 0){
        // Concurrent Modification Exception
        map.remove(tempKey);// DO NOT USE THIS

        //ALWAYS REMOVE USING ITERATOR
        itr.remove();
    }
}

MAP (Not part of Collection Framework)

There are 3 classes that implements the Map interface

1) HashMap: (IMPLEMENTATION OF HASHTABLE) This is “the map”, able to store key-value pairs, and able to find the value according to the key in O(1) if the hash function is perfect/good

  • PROBLEM: makes no guarantee about the order of iteration

2) TreeMap: it supports ordering –> natural ordering, compareTo() method or Comparator is important to be able to decide the order in case of non primitive objects !!!

3) LinkedHashMap: it contains a doubly linked list connecting all the entries in the map

  • Unlike HashMap it preserves insertion-order
  • insertion order is not affected if a key is re-inserted into the map
  • IMPORTANT: they consume more memory than HashMap !!!
  1. Count the number of Characters in a String
  2. Count the number of occurances