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}

No comments:

Post a Comment