Sunday 2 July 2017

Map Collection

A Map is an object that maps keys to values, or is a collection of Key-Value pairs.


To know more about Map Collection follow post Map Collection.

Note that a Map is not considered to be a true collection, as the Map interface does not extend the Collection interface. Instead, it starts an independent branch in the Java Collections Framework, as shown in the following diagram:


Because a Map is not a true collection, its characteristics and behaviors are different than the other collections like List or Set.

A Map cannot contain duplicate keys and each key can map to at most one value. Some implementations allow null key and null value (HashMap and LinkedHashMap) but some does not (TreeMap).

The order of a map depends on specific implementations, e.g TreeMap and LinkedHashMap have predictable order, while HashMap does not.


Why and When Use Maps:

Maps are perfect for key-value association mapping such as dictionaries. Use Maps when you want to retrieve and update elements by keys, or perform look-ups by keys. Some examples:

  • A map of zip codes and cities.
  • A map of managers and employees. Each manager (key) is associated with a list of employees (value) he manages.
  • A map of classes and students. Each class (key) is associated with a list of students (value).

This tutorial provides code examples around the three major implementations of Map which are described below.

Implementations of Map:

In the inheritance tree of the Map interface, there are several implementations but only 3 major, common, and general purpose implementations - they are HashMap and LinkedHashMap and TreeMap. Let’s see the characteristics and behaviors of each implementation:
  • HashMap: this implementation uses a hash table as the underlying data structure. It implements all of the Map operations and allows null values and one null key. This class is roughly equivalent to Hashtable - a legacy data structure before Java Collections Framework, but it is not synchronized and permits nulls. HashMap does not guarantee the order of its key-value elements. Therefore, consider to use a HashMap when order does not matter and nulls are acceptable. 
  • LinkedHashMap: this implementation uses a hash table and a linked list as the underlying data structures, thus the order of a LinkedHashMap is predictable, with insertion-order as the default order. This implementation also allows nulls like HashMap. So consider using a LinkedHashMap when you want a Map with its key-value pairs are sorted by their insertion order. 
  • TreeMap: this implementation uses a red-black tree as the underlying data structure. A TreeMap is sorted according to the natural ordering of its keys, or by a Comparator provided at creation time. This implementation does not allow nulls. So consider using a TreeMap when you want a Map sorts its key-value pairs by the natural order of the keys (e.g. alphabetic order or numeric order), or by a custom order you specify.So far you have understood the key differences of the 3 major Map’s implementations. And the code examples in this tutorial are around them.
Now, let’s see how to use Map for your daily coding.


Creating different Maps:

Creating HashMap:

Always use interface type (Map), generics and diamond operator to declare a new map. Creating any Map is as same as creating any other variable n Java. Below is the way how different implementation of Maps, most importantly HashMap, LinkedHashMap or TreeMap are created.


Map<Integer, String> hashMap = new HashMap<>();
Map<Integer, String> linkedHashMap = new LinkedHashMap<>();
Map<Integer, String> treeMap = new TreeMap<>();


Only there is a difference in creating different Maps but the most important useful operations are same across all Maps. So we use HashMap in all our examples to explain different most important Map operations(Methods).

Most important basic operations of a Map are association (put), lookup (get), checking (containsKey and containsValue), modification (remove and replace) and cardinality (size and isEmpty).


put Method:

The put(K, V) method associates the specified value V with the specified key K. If the map already contains a mapping for the key, the old value is replaced by the specified value:


package com.training.java.car;

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

public class MapsDemo {

 public static void main(String[] args) {
  Map<Integer, String> map = new HashMap<>();
  //Adding value in a Key and Value pair combination
  map.put(505001, "Hyderabad");
  map.put(110001, "New Delhi");
  map.put(400001, "Mumbai");
 }
}


get Method:

The get(Object key) method returns the value associated with the specified key, or returns null if the map contains no mapping for the key. Given the map in the previous example:


package com.training.java.car;

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

public class MapsDemo {

 public static void main(String[] args) {
  Map<Integer, String> zipCodes = new HashMap<>();
  // Adding value in a Key and Value pair combination
  zipCodes.put(505001, "Hyderabad");
  zipCodes.put(110001, "New Delhi");
  zipCodes.put(400001, "Mumbai");

  System.out.println("Getting the value Hyderabad with it's key: " + zipCodes.get(505001));
 }
}

Output:
Getting the value Hyderabad with it's key: Hyderabad


containsKey Method:

The method containsKey(Object key) returns true if the map contains a mapping for the specified key. For example:


package com.training.java.car;

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

public class MapsDemo {

 public static void main(String[] args) {
  Map<Integer, String> zipCodes = new HashMap<>();
  // Adding value in a Key and Value pair combination
  zipCodes.put(505001, "Hyderabad");
  zipCodes.put(110001, "New Delhi");
  zipCodes.put(400001, "Mumbai");

  System.out.println("Does map contains 505001 as key: " + zipCodes.containsKey(505001));
 }
}

Output:
Does map contains 505001 as key: true


containsValue Method:

The method containsValue(Object value) returns true if the map contains one or more keys associated with the specified value. For example:


package com.training.java.car;

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

public class MapsDemo {

 public static void main(String[] args) {
  Map<Integer, String> zipCodes = new HashMap<>();
  // Adding value in a Key and Value pair combination
  zipCodes.put(505001, "Hyderabad");
  zipCodes.put(110001, "New Delhi");
  zipCodes.put(400001, "Mumbai");

  System.out.println("Does map contains value Mumbai: " + zipCodes.containsValue("Mumbai"));
 }
}

Output:
Does map contains value Mumbai: true


remove Method:

The remove(Object key) method removes the mapping for a key from the map if it is present (we care about only the key, and the value does not matter). This method returns the value to which the map previously associated the key, or null if the map doesn’t contain mapping for the key. Here’s an example:


package com.training.java.car;

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

public class MapsDemo {

 public static void main(String[] args) {
  Map<Integer, String> zipCodes = new HashMap<>();
  // Adding value in a Key and Value pair combination
  zipCodes.put(505001, "Hyderabad");
  zipCodes.put(110001, "New Delhi");
  zipCodes.put(400001, "Mumbai");

  System.out.println("Map before removing: " + zipCodes);
  zipCodes.remove(505001);
  System.out.println("Map after removing: " + zipCodes);
 }
}

Output:
Map before removing: {110001=New Delhi, 400001=Mumbai, 505001=Hyderabad}
Map after removing: {110001=New Delhi, 400001=Mumbai}


replace Method:

The replace(K key, V value) method replaces the entry for the specified key only if it is currently mapping to some value. This method returns the previous value associated with the specified key. Here’s an example:


package com.training.java.car;

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

public class MapsDemo {

 public static void main(String[] args) {
  Map<Integer, String> zipCodes = new HashMap<>();
  // Adding value in a Key and Value pair combination
  zipCodes.put(505001, "Hyderabad");
  zipCodes.put(110001, "New Delhi");
  zipCodes.put(400001, "Mumbai");

  System.out.println("Map before replacing: " + zipCodes);
  zipCodes.replace(505001, "Secunderabad");
  System.out.println("Map after replacing: " + zipCodes);
 }
}

Output:
Map before replacing: {110001=New Delhi, 400001=Mumbai, 505001=Hyderabad}
Map after replacing: {110001=New Delhi, 400001=Mumbai, 505001=Secunderabad}


size Method:

The size()method returns the number of key-value mappings in this map. For example:


package com.training.java.car;

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

public class MapsDemo {

 public static void main(String[] args) {
  Map<Integer, String> zipCodes = new HashMap<>();
  // Adding value in a Key and Value pair combination
  zipCodes.put(505001, "Hyderabad");
  zipCodes.put(110001, "New Delhi");
  zipCodes.put(400001, "Mumbai");

  System.out.println("Map size: " + zipCodes.size());
 }
}

Output:
Map size: 3


clear Method: 

The clear() method removes all mappings from the map. The map will be empty after this method returns.
isEmpty Method:


The isEmpty() method returns true if the map contains no key-value mappings.

Let's see both clear and isEmpty methods in an example:


package com.training.java.car;

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

public class MapsDemo {

 public static void main(String[] args) {
  Map<Integer, String> zipCodes = new HashMap<>();
  // Adding value in a Key and Value pair combination
  zipCodes.put(505001, "Hyderabad");
  zipCodes.put(110001, "New Delhi");
  zipCodes.put(400001, "Mumbai");

  // Reset map i.e. clear all existing entries
  zipCodes.clear();
  // Size becomes Zero as we cleared all entries
  System.out.println("Map size: " + zipCodes.size());
 }
}

Output:
Map size: 0


putAll Method:

The putAll(Map<K, V> m) method copies all of the mappings from the specified map to this map. Here’s an example:




package com.training.java.car;

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

public class MapsDemo {

 public static void main(String[] args) {
  Map<Integer, String> zipCodes = new HashMap<>();
  // Adding value in a Key and Value pair combination
  zipCodes.put(505001, "Hyderabad");
  zipCodes.put(110001, "New Delhi");
  zipCodes.put(400001, "Mumbai");

  // Let's create another Map with no entries
  Map<Integer, String> pinCodes = new HashMap<>();
  // Coping all zipCodes map entries to pinCodes Map
  pinCodes.putAll(zipCodes);
  System.out.println("pinCodes Map entries: " + pinCodes);
 }
}

Output:
pinCodes Map entries: {110001=New Delhi, 505001=Hyderabad, 400001=Mumbai}

No comments:

Post a Comment