Collections : Maps

A Map is an object that maps keys to values. A map cannot contain duplicate keys. Each key can map to at most one value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types. Since Map is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between HashMap, Hashtable, LinkedHashMap, TreeMap, Properties etc.

Lets see an example:


package mynotes.collections.maps;

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

public class MapBasics {

public static void main(String[] args) {
 Map<Integer, String> myMap = new HashMap<Integer, String>();
 myMap.put(1, "One");
 myMap.put(2, "Two");
 myMap.put(3, "Three");

String value = (String) myMap.get(2);
 System.out.println(value);

}

}


The output will be ‘Two’. We can do it without using Generics buts it always recommended to use it for type safety.

You can iterate either the keys or the values of a Map.


// key iterator
 Iterator<Integer> keyIterator = myMap.keySet().iterator();
 System.out.println("Keys:");
 while (keyIterator.hasNext()) {
 Integer keys = (Integer) keyIterator.next();
 System.out.println(keys);

}
 // value iterator
 Iterator<String> valueIterator = myMap.values().iterator();
 System.out.println("Values:");
 while (valueIterator.hasNext()) {
 String values = (String) valueIterator.next();
 System.out.println(values);

}

Output:


Keys:
1
2
3
Values:
One
Two
Three

Another way to loop around all the values:


for(Integer key : myMap.keySet()) {
 Object obj = myMap.get(key);
 System.out.println(obj);
 }

In order to remove an item from a Map you can use remove(Object key) method. However as discussed in List, removing should only be done using an Iterator. For example if you try removing an item like this:


//removing item the wrong way
 for(Integer key : myMap.keySet()) {
 if(key==2){
 myMap.remove(key);
 }
 }

Output:


Exception in thread "main" java.util.ConcurrentModificationException

The correct wat to remove an item:


Iterator<Integer> interatorToRemove=myMap.keySet().iterator();
 while (interatorToRemove.hasNext()) {
 Integer integer = (Integer) interatorToRemove.next();
 if(integer==2){
 interatorToRemove.remove();
 System.out.println("Removed");
 }
 
 }

 

 

Difference between HashMap and HashTable

 

HashMap Hashtable (legacy)
HashMap lets you have null values as well as one null key. HashTable does not allows null values as key and value.
The  iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know). The enumerator for the Hashtable is not fail-safe.
HashMap is unsynchronized. Hashtable is synchronized.

If you have multiple thread accessing you HashMap then Collections.synchronizedMap(Map<K,V> m) can be used.

To make you map unmodifiable, you can call Collection method: Collections.unmodifiableMap(myMap);

Now if you try to put/remove things into your map you will get java.lang.UnSupportedOperation Exception

The LinkedHashMap implementation is a subclass of the HashMap class. Elements of a HashMap are unordered. The elements of a LinkedHashMap are ordered. By default, the entries of a LinkedHashMap are in key insertion order, that is, the order in which the keys are inserted in the map. This order does not change if a key is re-inserted, because no new entry is created if the key’s entry already exists. A LinkedHashMap can also maintain its elements in (element) access order, that is, the order in which its entries are accessed, from least-recently accessed to most-recently accessed entries. This ordering mode can be specified in one of the constructors of the LinkedHashMap class. Adding, removing, and finding entries in a LinkedHashMap can be slightly slower than in a HashMap, as an ordered doubly-linked list has to be maintained.

TreeMap also maps a key and a value. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key’s class, or by the comparator provided at creation time.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: