21 Sept 2012

descending a hashmap in java by key

//descending a hashmap in java by key
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class SortMapExample
{
   public static void main(String[] args)
   {
    Map<String,String> unsortMap=new HashMap<String,String>();
    unsortMap.put("2", "A");
    unsortMap.put("4", "B");
    unsortMap.put("1", "D");
    unsortMap.put("6", "c");
    unsortMap.put("3", "d");
    unsortMap.put("5", "C");
    unsortMap.put("7", "b");
    unsortMap.put("8", "a");
    System.out.println("Unsort Map......");
   
        for(Map.Entry entry : unsortMap.entrySet())
        {
     System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }

        System.out.println("Sorted Map......");
        Map<String,String> sortedMap=sortByComparator(unsortMap);

        for (Map.Entry entry : sortedMap.entrySet())
        {
    System.out.println("Key : "+entry.getKey()+" Value : "+entry.getValue());
        }
   }

   private static Map sortByComparator(Map unsortMap)
   {
        List list=new LinkedList(unsortMap.entrySet());
        //sort list based on comparator
        Collections.sort(list,new Comparator()
        {
             public int compare(Object o1,Object o2)
             {
     return ((Comparable)((Map.Entry)(o2)).getKey()).compareTo(((Map.Entry) (o1)).getKey());
             }
        });

        //put sorted list into map again
    Map sortedMap=new LinkedHashMap();
    for (Iterator it=list.iterator();it.hasNext();)
    {
         Map.Entry entry=(Map.Entry)it.next();
         sortedMap.put(entry.getKey(),entry.getValue());
    }
    return sortedMap;
   }   
}

Output:
Unsort Map......
Key : 3 Value : d
Key : 2 Value : A
Key : 1 Value : D
Key : 7 Value : b
Key : 6 Value : c
Key : 5 Value : C
Key : 4 Value : B
Key : 8 Value : a
Sorted Map......
Key : 8 Value : a
Key : 7 Value : b
Key : 6 Value : c
Key : 5 Value : C
Key : 4 Value : B
Key : 3 Value : d
Key : 2 Value : A
Key : 1 Value : D

0 comments:

Post a Comment