Order a TreeMap by its values

Java code: Demonstration to sort a TreeMap ascending/descending by its values

The script will works well, it only need to verify when there are repeated values.

 

 /*
     Sort a TreeMap by its values as seen in: http://kickjava.com/753.htm
     I've improved this code by eliminating some warnings related to generic types
   
      1. Create a TreeSet of key/value pairs where the Comparator sorts by  
         the *value*  ( the Double )  in each pair.  
      2. Get the key/value pairs from the original TreeMap by calling  
         TreeMap.entrySet (  )  
      3. Add all the pairs from 2 into the TreeSet in 1.  
   
   */
     
  import java.util.Comparator;  
  import java.util.Iterator;  
  import java.util.Map;  
  import java.util.Set;  
  import java.util.TreeMap;  
  import java.util.TreeSet;  
   
     
  public class SortedValue  
   {  
      public static void main (  String [  ]  args  )  
       {  
          Map map = new TreeMap();

          map.put (  "1/4", new Double (  0.25  )   ) ;  
          map.put (  "1/2", new Double (  0.5  )   ) ;  
          map.put (  "1/16", new Double (  0.0625  )   ) ;  
          map.put (  "1/8", new Double (  0.125  )   ) ;  
         
          Set set = new TreeSet(  
             new Comparator (  )  
               {  
                  public int compare (  Object o1, Object o2  )  
                   {  
                      Map.Entry e1 =  ( Map.Entry ) o1;  
                      Map.Entry e2 =  ( Map.Entry ) o2;  
   
                      Double d1 =  ( Double ) e1.getValue (  ) ;  
                      Double d2 =  ( Double ) e2.getValue (  ) ;  
   
                     // ASC
             // return d1.compareTo (  d2  ) ;  
              // DESC
                     return d2.compareTo (  d1  ) ;  
                     
                   }  
               }   ) ;  
   
          set.addAll (  map.entrySet (  )   ) ;  
   
          for  (  Iterator iter = set.iterator (  ) ; iter.hasNext (  ) ;  )  
           {  
              Map.Entry entry =  ( Map.Entry ) iter.next (  ) ;  
              System.out.println (  entry.getKey (  )  + " = " + entry.getValue (  )   ) ;  
           }  
       }  
   }  
   
 /*
   
 This will output the following:  
   
 1/2 = 0.5
 1/4 = 0.25
 1/8 = 0.125
 1/16 = 0.0625

 */