Advertisement
Guest User

Untitled

a guest
Jan 2nd, 2011
676
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. package util;
  2.  
  3. import java.util.Collections;
  4. import java.util.Comparator;
  5. import java.util.HashMap;
  6. import java.util.Iterator;
  7. import java.util.LinkedList;
  8. import java.util.LinkedHashMap;
  9. import java.util.List;
  10. import java.util.Map;
  11.  
  12. public class SortableValueMap<K, V extends Comparable<? super V>>
  13.   extends LinkedHashMap<K, V> {
  14.   public SortableValueMap() { }
  15.  
  16.   public SortableValueMap( Map<K, V> map ) {
  17.     super( map );
  18.   }
  19.  
  20.   public void sortByValue() {
  21.     List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>( entrySet() );
  22.  
  23.     Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
  24.       public int compare( Map.Entry<K, V> entry1, Map.Entry<K, V> entry2 ) {
  25.         return entry2.getValue().compareTo( entry1.getValue() );
  26.       }
  27.     });
  28.  
  29.     clear();
  30.  
  31.     for( Map.Entry<K, V> entry : list ) {
  32.       put( entry.getKey(), entry.getValue() );
  33.     }
  34.   }
  35.  
  36.   private static void print( String text, Map<String, Double> map ) {
  37.     System.out.println( text );
  38.  
  39.     for( String key : map.keySet() ) {
  40.       System.out.println( "key/value: " + key + "/" + map.get( key ) );
  41.     }
  42.   }
  43.  
  44.   public static void main(String[] args) {
  45.     SortableValueMap<String, Double> map =
  46.       new SortableValueMap<String, Double>();
  47.  
  48.     map.put( "A", 67.5 );
  49.     map.put( "B", 99.5 );
  50.     map.put( "C", 82.4 );
  51.     map.put( "D", 42.0 );
  52.  
  53.     print( "Unsorted map", map );
  54.     map.sortByValue();
  55.     print( "Sorted map", map );
  56.   }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement