Tuesday, January 28, 2014

Java Collection :Map Interface

Map is used to map between keys and values. Key, Value pair is called Entry.Map doesn't allow duplicate keys.Keys and Values must be objects. No primitive types are allowed.Map is not a collection.Mapping can be viewed as collections by keySet, a value collection and EntrySet



package collections;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class MapTest {
       public static void main(String[] args) {

              // Basic Operations
              HashMap<String, String> m = new HashMap<String, String>();
              m.put("key1", "Value1");
              m.put("key2", "Value2");
              m.put("key3", "Value3");
              m.put("key4", "Value3");

              System.out.println(m.get("key1"));

              m.remove("key1");
              System.out.println(m);

              System.out.println(m.containsKey("key4"));
              System.out.println(m.containsValue("Value3"));
              System.out.println(m.size());
              System.out.println(m.isEmpty());

              // Bulk Operations

              Map<String, String> m1 = new HashMap<String, String>();
              m1.putAll(m);
              System.out.println(m);
              System.out.println(m1);

              m1.clear();
              System.out.println(m1);

              // Collections views
              System.out.println(m.keySet());
              System.out.println(m.values());
              System.out.println(m.entrySet());
              Iterator<Entry<String, String>> itr = m.entrySet().iterator();
              while (itr.hasNext()) {
                     Entry<String, String> e = itr.next();
                     System.out.println(e.getKey() + " : " + e.getValue());
              }
       }
}


Map Implementations

HashMap,LinkedHashMap and Hashtable classes are using Map ineterface. HashMap and HashTable are unordered maps.LinkedHashMap is an ordered map. TreeMap is a sorted map.HashMap allows one null value as key . Hashtable is threadsafe and doesn't allow null values. Hashtable's threadsafe features comes with a performance penalty for synchronization.Map implementation is based on hashing algorithms.It relay on hashcode() and equals() implementation.LinkedHashMap is subclass of HashMap.LinkedHashMap's ordering is by default is key insertion order.LinkedHashMap also maintains keys in access order. Ordering mode can be specified in the constructor. Adding removing and searching of LinkedHashMap is slightly slower than HashMap.Traversal of HashMap is through Collection views.



package collections;

import java.util.LinkedHashMap;

public class MapImplTest {
       public static void main(String[] args) {

              // Constructors
              LinkedHashMap<String, String> lm = new LinkedHashMap<String, String>();
              LinkedHashMap<String, String> lm1 = new LinkedHashMap<String, String>(10);// with initial capaity
              LinkedHashMap<String, String> lm2 = new LinkedHashMap<String, String>(10, 1);// initial capacity and loadfactor
              LinkedHashMap<String, String> lm3 = new LinkedHashMap<String, String>(10, 1, true);// With access order . Key
                                                                                                                                                              // insertion order 3rd param
                                                                                                                                                              // =false

              System.out.println(lm + " " + lm1 + " " + lm2 + " " + lm3);
       }

}

SortedMap<K,V> and NavigableMap<K,V> Interfaces

SortedMap<K,V>
SortedMap extends Map interface . SortedMaps are maps with sorted keys

NavigableMap<K,V>

NavigableMap extends SortedMap.NavigableMap is prefrerred choice thanSortedMap.

TreeMap Class

TreeMap is sorted Map.TreeMap implements Navigable map and there by sorted.TreeMap has by default natural ordering but Comparators are supported.TreeMap provides balanced trees and provides excellent performance.Searching HashMap is faster than TreeMap as the hashing algorithm provides better performance than TreeBased algorithm.

package collections;

import java.util.HashMap;
import java.util.Map;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;

public class TreeMapTest {
    public static void main(String[] args) {

        HashMap<String, String> hm = new HashMap<String, String>();
        hm.put("ke1", "Value1");
        hm.put("ke2", "Value2");
        hm.put("ke3", "Value3");
        hm.put("ke4", "Value4");
        hm.put("ke5", "Value5");

        SortedMap<String, String> m = new TreeMap<String, String>(hm);
        System.out.println(m);
        System.out.println(m.firstKey()); // Set is empty NoSuchEmenetException
        System.out.println(m.lastKey());

        System.out.println(m.headMap("ke3"));// toKey
        System.out.println(m.tailMap("ke3"));// formKey

        System.out.println(m.comparator());// Null if no comparator

        NavigableMap<String, String> nm = new TreeMap<String, String>(hm);

        System.out.println(nm);

        Map.Entry<String, String> me1 = nm.firstEntry();
        System.out.println(me1.getKey() + " : " + me1.getValue());

        Map.Entry<String, String> me2 = nm.lastEntry();
        System.out.println(me2.getKey() + " : " + me2.getValue());

        System.out.println(nm);

        nm.pollFirstEntry();// remove first entry
        nm.pollLastEntry();// remove last entry

        System.out.println(nm);

        nm = new TreeMap<String, String>(hm);
        System.out.println(nm);

        System.out.println(nm.headMap("ke3", true));// toElement,inclusive
        System.out.println(nm.headMap("ke3", false));

        System.out.println(nm.tailMap("ke3", true));// fromElement,inclusive

        System.out.println(nm.subMap("ke2", true, "ke4", false));// toElement,inclusive,fromElement,inclusive

        // Closest Match

        Map.Entry<String, String> ce = nm.ceilingEntry("ke3");
        System.out.println(ce.getKey() + " : " + ce.getValue());

        ce = nm.floorEntry("ke3");
        System.out.println(ce.getKey() + " : " + ce.getValue());

        ce = nm.higherEntry("ke3");
        System.out.println(ce.getKey() + " : " + ce.getValue());

        ce = nm.lowerEntry("ke3");
        System.out.println(ce.getKey() + " : " + ce.getValue());

        System.out.println(nm.descendingMap()); // Descending map
        System.out.println(nm.descendingKeySet());// Descending keys
        System.out.println(nm.navigableKeySet());// forward order keys
    }

}


No comments: