Showing posts with label Collection Framework. Show all posts
Showing posts with label Collection Framework. Show all posts

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 24 July 2013

What is Comparator and Comparable interface in java and what are the differences between them?



The Array.sort() and Collections.sort() can sort array and arraylist on the basis of single values but Lists are meant to store objects and they can have multiple properties so if need to sort list on the basis of some other properties than we need to use Comparable and Comparator interfaces.

Basically, Collections.sort()  have two types in java collection framework .
  1. Collections.sort(List of objects of class which implements Comparable   or list of objects);
  2. Collections.sort(list of objects, object of class implementing Comparator);

Comparable Interface: When we use Collection.sort() with single arguments or first type of Collections.sort then it basically needs the object of the class and the class should implement Comparable interface of Java.lang package.Comparable interface of java has an abstract method compareTo(Class object) which need to be implemented every time the class implements the Comparable interface. This method is containing the logic for sorting the list on the basis of some property. It compares the property with object property and returns the integer type result as:
Positive    – this object is greater than object’s property
Zero          – Both properties are equal
Negative – this object is less than object’s property

Let‘s suppose that we have a class containing the employee data(Emp Name, Emp Age). Now we can sort the list on the basis of name as well as age with the help of Comparator (refer below example).

 import java.util.*;

class empData implements Comparable<empData>
{
    String name="";
    int age=0;
    empData()    {    }
    empData(String name, int age)  {
          this.name= name;
          this.age=age;
      }

     public int compareTo(empData obj)    {
         // return this.age - obj.age;   /*If we uncomment this line and comment the line below it will sort  
                                                                the list on the basis of employee name*/
         return this.name.compareTo(obj.name); //This will sort the list on the basis of employee age
         }
 }
     
public class demoComparable
      {
        public static void main(String s[])      {
          List<empData> list = new ArrayList<empData>();
          list.add(new empData("B",50));
          list.add(new empData("A",30));
           list.add(new empData("e",25));
            list.add(new empData("c",45));
             list.add(new empData("d",52));
          System.out.println("List before sorting");
          for(empData a : list)  {

                System.out.print(a.name+"  ");
                System.out.println(a.age);   }

/*Calling the sort by passing the list of empData Class objects which implements Comparable interface */
Collections.sort(list); 
          System.out.println("List after sorting");
          for(empData a : list)
          {
                System.out.print(a.name+"  ");
                System.out.println(a.age); }}}
      
Comparator Interface: When we use Collection.sort() with two arguments or second type of Collections.sort then it basically needs the object of the class and the class should implement Comparator interface of Java.util  package. Comparable interface of java has an abstract method compare(Class object 1,class object2) which need to be implemented every time the class implements the Comparator interface. This method is containing the logic for sorting the list on the basis of some property. It compares the object2 property with object1 property and returns the integer type result as:
Positive    – Object1 property is greater than object 2 property
Zero          – Both properties are equal
Negative – Object1 property is less than object 2 property

Same above example can be recreated as below example to understand the concept of Cmparator sorting.

import java.util.*;

class empData implements Comparator<empData>
{
    String name="";
    int age=0;
    empData()    {    }
    empData(String name, int age)  {
          this.name= name;
          this.age=age;
      }

     public int compare(empData a, empData b){
         // return a.age - b.age;   /*If we uncomment this line and comment the line below it will sort  
                                                                the list on the basis of employee name*/
         return a.name.compareTo(b.name); //This will sort the list on the basis of employee age
         }
 }
     
public class demoComparator
      {
        public static void main(String s[])      {
          List<empData> list = new ArrayList<empData>();
          list.add(new empData("B",50));
          list.add(new empData("A",30));
           list.add(new empData("e",25));
            list.add(new empData("c",45));
             list.add(new empData("d",52));
          System.out.println("List before sorting");
          for(empData a : list)  {

                System.out.print(a.name+"  ");
                System.out.println(a.age);   }

/*Calling the sort by passing the list of empData Class objects  and object of the class which implement the comparator(it can be same class whose properties need to be sort or any other class implementing the comparator interface)*/
Collections.sort(list,new empData());
          System.out.println("List after sorting");
          for(empData a : list)
          {
                System.out.print(a.name+"  ");
                System.out.println(a.age); }}}


Differences between Comparator and Comparable

S.No.
Comparable
Comparator
1
Comparable comes under JAVA.LANG Package
Comparator comes under JAVA.UTIL Package
2
It has an abstract method compareTo(class type variable)
It has an abstract method compare(class type variable1 ,class type variable2)
3
The class whose properties need to be sort must implement Comparable interface that’s why they provide natural ordering
The class whose properties need to be sort may or may not implement Comparator interface. Some other class can have the sorting logic or can implement Comparator interface.
4
It is called when Collections.sort(list) is called
It is called when Collections.sort(list, comparator) is called