HashMap sorted based on values…

By sumedhinamdar

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 :(

2 Responses to “HashMap sorted based on values…”

  1. resimler Says:

    he yaaa

  2. ounos Says:

    First of all, reporting errors through System.out.println’s, and even more returning 0, is simply hideous. Please kill this beast.

    Secondly, this code is broken, unless you really want to access only one key of all the keys having an “equal” value.

    Thirdly, it’s always nice to take a O(1) method and override it with a O(nlogn) implementation. And works only with HashMap since you decided to extend this particular class. Anyway, and what does all of this effort buy you? Why not maintain a TreeMap with the inverted entries, but resorting and resorting for every single keySet() method call?

Leave a Reply