Friday, 23 August 2013

How to sort HashTable and HashMap in java collection?



Map interface does not provide a direct sort() method like collection interface so we have to sort them manually. We took the example of HashMap and HashTable for sorting. HashMap is by default sorted on the basis of Key but HashTable is not sorted at all. 

1 - Hashtable sorting:
We have two ways to sort HashTable.
  • On the basis of key.
HashTable  --> TreeMap or HashMap
  • On the basis of value.
HashTable --> ArrayList --> Comparator sorting of ArrayList --> convert to map again

Example Code:-
 import java.util.*;
public class demoSortHashTable
{
 public static void main(String s[])
        {
            Map mp = new Hashtable();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
          
            System.out.println("Print HashTable contents without sorting");
            System.out.println(mp);

           //First way to sort hashmap by converting it to TreeMap(it will sort on the basis of key)
           System.out.println("HashTable contents after sorting by key");
           Map mpt = new HashMap(mp);
           System.out.println(mpt);

           //Second way to sort hashmap by converting it to List(it will sort on the basis of value also)
           System.out.println("HashTable contents after sorting by value");
           //Converting HashMap to ArrayList
           List lt = new ArrayList(mp.entrySet());
           //Sorting the ArrayList with Comparator
           Collections.sort(lt, new Comparator() {
                                                public int compare(Object o1, Object o2) {
                                                                return ((Comparable) ((Map.Entry) (o1)).getValue())
                                       .compareTo(((Map.Entry) (o2)).getValue());
                                                }
                                });
            //Putting the value of the List into LinkedHashSet
            Map mp1 = new LinkedHashMap();
            Iterator it1 = lt.iterator();
            while (it1.hasNext())
             {
                 Map.Entry ent = (Map.Entry) it1.next();
                 mp1.put(ent.getKey(),ent.getValue());
             }
          System.out.println(mp1);
        }
}

Output:
Print HashTable contents without sorting
{4=Fourth, 3=Third, 2=Second, 1=First}
HashTable contents after sorting by key
{1=First, 2=Second, 3=Third, 4=Fourth}
HashTable contents after sorting by value
{1=First, 4=Fourth, 2=Second, 3=Third}



2 - HashMap sorting:
HashMap is sorted by default (on key) so we just need to sort it on the basis of Value if needed.

Example Code:
import java.util.*;
public class demoSortHashMap
{
 public static void main(String s[])
        {
            Map mp = new HashMap();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
            System.out.println("HashMap contents are sorted on keys by default");
            System.out.println(mp);

          //Sort hashmap by converting it to List(it will sort on the basis of value also)
           System.out.println("HashMap after sorting by value");
           //Converting HashMap to ArrayList
           List lt = new ArrayList(mp.entrySet());
           //Sorting the ArrayList with Comparator
           Collections.sort(lt, new Comparator() {
                                                public int compare(Object o1, Object o2) {
                                                                return ((Comparable) ((Map.Entry) (o1)).getValue())
                                       .compareTo(((Map.Entry) (o2)).getValue());
                                                }
                                });
            //Putting the value of the List into LinkedHashSet
            Map mp1 = new LinkedHashMap();
            Iterator it1 = lt.iterator();
            while (it1.hasNext())
             {
                 Map.Entry ent = (Map.Entry) it1.next();
                 mp1.put(ent.getKey(),ent.getValue());
             }
          System.out.println(mp1);
        }
}

Output: -
HashMap contents are sorted on keys by default
{1=First, 2=Second, 3=Third, 4=Fourth}
HashMap after sorting by value
{1=First, 4=Fourth, 2=Second, 3=Third}

Thursday, 22 August 2013

How to traverse HashMap and HashTable with iterator in Java Collection framework?



Traversing Map interface is bit differ from traversing the collection interface because we have key, Value pair is stored in map and we have to traverse them as a set. We use some properties of Map interface to do the work like Map.Entry, Map.entryset(), which are used to tackle key, value pair as set. We can get the value of key and value with getKey() and getValue() methods from object of Map.Entry type. Please see the program below to understand it more clearly.
In below examples, we traversed both HashMap and Hashtable. There is no difference between traversing of them, the only difference is the output of both program.  The HashMap produce a sorted output but Hashtable  produce a unsorted output (As per their properties).

1 - Traverse HashMap with Iterator Example:
import java.util.*;
public class demoTraverseHashMap
{
 public static void main(String s[])
        {
            Map mp = new HashMap();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
            System.out.println("Print MAP contents without traversing");
            System.out.println(mp);


           System.out.println("Print MAP contents with Iterator traversing");
           Iterator it = mp.entrySet().iterator();
           while(it.hasNext())
           {
               Map.Entry pairs = (Map.Entry) it.next();
               System.out.println("Key : "+pairs.getKey()+", Value : "+pairs.getValue());
           }
        }
}

OutPut:
Print MAP contents without traversing
{1=First, 2=Second, 3=Third, 4=Fourth}
Print MAP contents with Iterator traversing
Key : 1, Value : First
Key : 2, Value : Second
Key : 3, Value : Third
Key : 4, Value : Fourth


2 - Traverse HashTable with Iterator Example:
 import java.util.*;
public class demoTraverseHashMap
{
 public static void main(String s[])
        {
            Map mp = new Hashtable();
            mp.put(1,"First");
            mp.put(2,"Second");
            mp.put(3,"Third");
            mp.put(4,"Fourth");
            System.out.println("Print MAP contents without traversing");
            System.out.println(mp);


           System.out.println("Print MAP contents with Iterator traversing");
           Iterator it = mp.entrySet().iterator();
           while(it.hasNext())
           {
               Map.Entry pairs = (Map.Entry) it.next();
               System.out.println("Key : "+pairs.getKey()+", Value : "+pairs.getValue());
           }
        }
}

OutPut:
Print MAP contents without traversing
{4=Fourth, 3=Third, 2=Second, 1=First}
Print MAP contents with Iterator traversing
Key : 4, Value : Fourth
Key : 3, Value : Third
Key : 2, Value : Second
Key : 1, Value : First

Wednesday, 21 August 2013

Can we call init method in service method of servlet?

This is a very tricky question asked in an interview. The servlet lifecycle is a very important question in any java interview. The goal behind asking this question is to check the knowledge of servlet lifecycle of the candidate. This question can be modified in many ways like can we call destroy method in service method etc. (Read the link --http://javaitblog.blogspot.in/2013/04/what-happens-if-you-call-destroy-from.html). 
For the question “can we call init method in service method”, the direct answer is “Yes”. We can call init method in service method for any number of times. The init method initializes the ServletConfig parameter or initializes the servlet instance. The init method will be called by the container only once when it is started. So there is no use of calling it again in the service method but if we want, we can call it in the service method. To understand it more clearly, please see the below example.
Example Code:
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/demoCalInitMethod")
public class demoCalInitMethod extends HttpServlet {
                private static final long serialVersionUID = 1L;
                ServletConfig config;
                int count=0;
                  
    public demoCalInitMethod() {
        super();
    }

                public void init(ServletConfig config) throws ServletException {
                                this.config = config;
                                ++count;
                }
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
               
                                System.out.println("The value of count variable before calling init methods in service method :- "+count);
                                init(config);
                                init(config);
                                init(config);
                                init(config);
                                init(config);
                                System.out.println("The value of count variable before calling init methods in service method :- "+count);
                }

                protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                                                }

                protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                }

}

Output :-

The value of count variable before calling init methods in service method :- 1
The value of count variable before calling init methods in service method :- 6

In the above example, the init method is called in service method for five times. In init method, we incremented an integer type variable “count” with one so whenever this method is called it will increment the value of “count” variable by one. We printed the value of count variable in service method before and after calling the init method explicitly. As the output showing above, it printed the value of count 1 before calling the init methods explicitly (Because container calls it once automatically when it loads the servlet) and 6 after calling  the init methods explicitly because  we called the init method for five times in service method.
So init will initiate the servlet n times if call the init method n times with same ServletConfig object.