sort map by value

Class ValueComparator implements Comparator<String> {
    HashMap<String, Integer> map = new HashMap<String, Integer>();
    public ValueComparator(HashMap<String, Integer> map){
        this.map.putAll(map);
    }
    int compare(String key1, String key2){
        if(map.get(key1) < map.get(key2)){
            return 1;
        } else {
            return -1;
        }
    }
}
...
Comparator<String> comparator = new ValueComparator(originalMap);
TreeMap<String, Integer> result = new TreeMap<String, Integer>(comparator);
result.putAll(orignalMap);
return result;

java-sort-map-by-value

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