Map Interface

Map Interface

Map Interface cares about unique identification. It stores data as key-value pair where key and value both are objects. It let you  do search a value based on key or vice-versa.A map cannot contain duplicate key. Map implementations are :

HashMap
HashMap is an unsorted unordered Map.If you need Map and you dont care about order then go for it.
  • HashMap allows one null key and multiple null values in a collection.
  • Any class which is used as a part of keys for the map must override the hashCode() and equals() method,if you dont override then your code will compile and run but you just won't find your stuff.
import java.util.*;
 class Emp{
            public String name;
            public Emp(String s){
                        name=s;
            }
            public boolean equals(Object o){
                        if((o instanceof Emp) && (((Emp)o).name)==name){
                                    return true;
                        }else
                                    return false;
            }
            public int hashCode(){ return name.length();}
 }
 class Clerk{ }
 enum pets{DOG,CAT,HORSE};
 public class RajniHashMap {
            public static void main(String[] args) {
            Map<Object,Object> rajniMap = new HashMap<Object, Object>();
            rajniMap.put("k1",new Emp("Sam"));
            rajniMap.put("k2",pets.CAT);
            Emp e = new Emp("Max"); //Creating object of Emp
            rajniMap.put(e,"Emp Object");//using Emp object as key
            rajniMap.put(new Clerk(), "never retrieved");
           
            System.out.println(rajniMap.get("k1"));
            System.out.println(rajniMap.get("k2"));
            System.out.println(rajniMap.get(e));
            //Using Clerk object as a key which did not override hashCode()and equals().
            System.out.println(rajniMap.get(new Clerk()));
            }
 }
Output:

rajni.CandoAnyThing.Emp@3
CAT
Emp Object
null

More methods related to HashMap.

Hashtable
  • Like Vector, Hashtable is also legacy java class.
  • As Vector, Hashtable methods are also synchronized.
  • Unlike HashMap, Hashtable doesnot allow anything null.
  • To successfully store and retrieve the objects from Hashtable,objects used as key must override the hashCode() and equals() method.
 Hashtable constructors:

     Hashtable hTable = new Hashtable();  
     Hashtable hTable = new Hashtable(100);  //specifying initial capacity.
     Hashtable hTable = new Hashtable(Map myMap); //Creating Hashtable from Map.


import java.util.*;
 class Depositor{
            public String name;
            public Depositor(String s){
                        name=s;
            }
            public boolean equals(Object o){
                        if((o instanceof Depositor) && (((Depositor)o).name)==name){
                                    return true;
                        }else
                                    return false;
            }
            public int hashCode(){ return name.length();}
 }
 class Investor{ }
 public class RajniHashtable {
            public static void main(String[] args) {
            Map<Object,Object> rajniTable = new Hashtable<Object, Object>();
            rajniTable.put("d1",new Depositor("Sam"));
            rajniTable.put(new Depositor("Max"),"Object");//Depositor obj as key
            rajniTable.put(new Investor(), "never retrieved");
            rajniTable.put("one", 1);
 //         rajniTable.put(null, "NULL Value"); this will throw NullPointerException
           
            System.out.println("Number of keys :"+rajniTable.size());
            System.out.println("Retrieving all keys : Value");
            Set<Object> s = rajniTable.keySet();
            Iterator<Object> itr = s.iterator();
            Object str;
            while(itr.hasNext()){
                        str =  itr.next();
                        System.out.println(str+": "+rajniTable.get(str));
            }
            //Using Investor object as a key which did not override hashCode()and equals().
            System.out.println(rajniTable.get(new Investor()));
            }
 }
Output:


Number of keys :4
Retrieving all keys : Value
one: 1
rajni.CandoAnyThing.Investor@9304b1: never retrieved
rajni.CandoAnyThing.Depositor@3: Object
d1: rajni.CandoAnyThing.Depositor@3
null

More methods related to Hashtable.


TreeMap
  • TreeMap stores Key/Value pair in sorted order.By default elements will be sorted in ascending order.
  • If you need a Map for inserting,deleting and retrieving based on key and if order doesn't matter then HashMap is best option,and if you need to traverse the keys in sorted manner then TreeMap is best alternative.
  • HashMap is faster than TreeMap.
  • TreeMap is also not synchronized.
  • Class whose object is to be inserted in TreeMap must override hashCode() and equals() method otherwise you won't find your stuff.
  • Class whose object is to be stored in TreeMap must implements Comparator or Comparable interface and object must be mutually comparable.
public class RajniTreeMap {
   public static void main(String[] args) {
             TreeMap<Integer, String> rajniTMap = new TreeMap<Integer, String>();
             rajniTMap.put(1, "Sun");
             rajniTMap.put(2, "Mon");
             rajniTMap.put(3, "Tue");
             rajniTMap.put(4, "Wed");
             rajniTMap.put(5, "Thu");
             rajniTMap.put(6, "Fri");
             rajniTMap.put(7, "Sat");
             //Retrieving All keys/Value
             Set<Integer> s = rajniTMap.keySet();
             Iterator<Integer> itr = s.iterator();
             int i;
             while(itr.hasNext()){
                         i = itr.next();
                         System.out.println("Key :"+i+" Values :"+rajniTMap.get(i));
             }
             //Returning values in reverse order
            System.out.println(rajniTMap.descendingMap());
            //Returning reverse order of keys
            System.out.println(rajniTMap.descendingKeySet());
            //pollFirstEntry():Returns and removes the 1st key/value pair           
            System.out.println(rajniTMap.pollFirstEntry());
            //pollLastEntry():Returns and removes the 1st key/value pair
            System.out.println(rajniTMap.pollLastEntry());
            Iterator<Integer> itr1 = s.iterator();
            while(itr1.hasNext()){
                        i = itr1.next();
                        System.out.println("Key :"+i+" Values :"+rajniTMap.get(i));
             }
          }
 }
Output:



Key :1 Values :Sun
Key :2 Values :Mon
Key :3 Values :Tue
Key :4 Values :Wed
Key :5 Values :Thu
Key :6 Values :Fri
Key :7 Values :Sat
{7=Sat, 6=Fri, 5=Thu, 4=Wed, 3=Tue, 2=Mon, 1=Sun}
[7, 6, 5, 4, 3, 2, 1]
1=Sun
7=Sat
Key :2 Values :Mon
Key :3 Values :Tue
Key :4 Values :Wed
Key :5 Values :Thu
Key :6 Values :Fri

More methods related to TreeMap.


LinkedHashMap
  • LinkedHashMap implements HashMap and implements Map.It stores data as key/value pair.
  • LinkedHashMap maintains doubly-linked list through all its entries.
  • It maintains insertion order in which elements are inserted i.e. when iterating a LinkedHashMap,elements will be returned in the order in which they were inserted.
  • If you insert the key again into LinkedHasMap,the original order is retained.
LinkedHashMap Constructors :

      LinkedHashMap ()   // constructs empty insertion-ordered LinkedHashMap.
      LinkedHashMap (int initialCapacity)   // specifying initial capacity
      LinkedHashMap(Map m)  // creating insertion-ordered LinkedHashMap from the Map.
      LinkedHashMap(int initialCap,float LoadFac,boolean accessOrder) // discussed below.

import java.util.*;
 public class RajniLinkedHashMapDemo {
            public static void main(String[] args) {
              Map<Integer,String> rajniLHMap = new inkedHashMap<Integer,String>();
              rajniLHMap.put(1, "one");
              rajniLHMap.put(2, "two");
              rajniLHMap.put(3, "three");
              rajniLHMap.put(6, "Six");
              rajniLHMap.put(4, "four");
              rajniLHMap.put(5, "five");
              rajniLHMap.put(6, "six");
                                               
              System.out.println(rajniLHMap);
            }
 }
Output:
{1=one, 2=two, 3=three, 6=six, 4=four, 5=five}

A special constructor has been provided to create LinkedHashMap whose order of iteration is the order in which its entries were last access,from least-recently accessed to most-recently(access order).This type of map is well suited for creating LRU caches.

import java.util.*;
public class RajniLinkedHashMap {
     public static void main(String[] args) {
         /*Map rajniLHMap =
                               new LinkedHashMap(int initialCap,float loadFactor,boolean accessOrder);
            If accessOrder is true, then access order is used.
            If accessOrder is false, then insertion order is used.*/

         Map<Integer,String> rajniLHMap = new LinkedHashMap<Integer,String>( 4,1, true);
         rajniLHMap.put(1, "one");
         rajniLHMap.put(2, "two");
         rajniLHMap.put(3,"three");
         rajniLHMap.put(4, "four");
         rajniLHMap.put(5, "five");
         rajniLHMap.put(6, "six");

        //Retrieving the elements in isertion order.
        System.out.println(rajniLHMap);
        //Retrieving element individually
        System.out.println(rajniLHMap.get(2));
        System.out.println(rajniLHMap.get(1));
        System.out.println(rajniLHMap.get(3));
        /*Since 2,1,3 has been accessed recently so it will come after 4,5,6 which are least- recently accessed*/
        System.out.println(rajniLHMap);
   }
}

Output:



{1=one, 2=two, 3=three, 4=four, 5=five, 6=six}
two
one
three
{4=four, 5=five, 6=six, 2=two, 1=one, 3=three}

More methods related to LinkedHashMap.

1 comment:

  1. very usefull contents....keep up this good work...

    ReplyDelete