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 😦

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: