I want to sort a map by its values. But the compare method is already in the class.
public class Parser implements Comparator<String> {
private Map<String, Integer> frequencies;
public Parser() {
frequencies = new HashMap<String, Integer>();
}
public int getCount(String word) {
Integer c = frequencies.get(word);
if (c == null) {
return 0;
}
else {
return c.intValue();
}
}
public int compare(String o1, String o2) {
int count1 = getCount(o1);
int count2 = getCount(o2);
return count1 < count2 ? -1 : count1 > count2 ? 1 : 0;
}
public List<String> getWordsInOrderOfFrequency(){
TreeMap<String,Integer> sorted_map = new TreeMap<String,Integer>();
sorted_map.putAll(frequencies);
ArrayList<String> result = new ArrayList<String>(sorted_map.keySet());
return result;
}
}
Here the question is in the getWordsInOrderOfFrequenct() method. I want to sort the keyset by its values after compared.