Sunday, June 24, 2007

HashMap sorted based on values...

Just wrote a simple HashMap class to have entries sorted based on values...i.e. the keySet() method will return the keys based on sorted order of their corresponding values...

Here it goes...


import java.util.*;
import java.util.*;

/**
* HashMap with entries sorted based on Values. (keySet() method will return keys sorted based on values.)
* @author Sumedh Inamdar
*/
public class ValueSortedHashMap extends HashMap {
  
  public Set keySet() {
    TreeSet s = new TreeSet(new MapValueComparator(this));
    s.addAll(super.keySet());
    return s;
  }
  
  /**
   * Comparator class for comparing keys based on values. Assumes that values are 'Comparable'.
   */
  class MapValueComparator implements Comparator {
    MapValueComparator(Map m) {
      map = m;
    }
   public int compare(Object k1, Object k2) {
     if(!(map.get(k1) instanceof Comparable)) {
       System.out.println("ERROR...ValueSortedHashMap could not compare the values...");
       return 0;
     }
     return ((Comparable)map.get(k1)).compareTo(map.get(k2));
   }
   Map map;
  }
}

By the way...does any one know a quick way to post formatted code on site? This was pain in a$$...Blogger just removes my spaces after I do some editing...and for even adding spaces, I had to hack it like this :(

No comments: