Reputation: 3707
I have a map: TreeMap<String, Integer> m = new TreeMap<>();
where I have a whole alphabet and values, which shows how many times each letter was found in my text.
I want to sort that map in descending count order; that is, the most frequent letter is on the first line, and the last line of output indicates the least frequent letter. If two letters have the same frequency, then the letter which comes first in the alphabet must appear first. How to make it?
I tried with Comparator:
public int compare(String a, String b) {
if (base.get(a) >= base.get(b) && a.compareToIgnoreCase(b) < 0) {
return -1;
} else {
return 1;
}
}
but still, its not it, the output is:
D 3
E 3
A 2
S 5
Guys ... Found this before, this didnt help at all. Good output should be:
S 5
D 3
E 3
A 2
Upvotes: 6
Views: 3563
Reputation: 328618
Your comparator does not look right - this should work better:
public int compare(String a, String b) {
if (base.get(a) > base.get(b)) {
return -1;
} else if (base.get(a) < base.get(b)) {
return 1;
} else {
int stringCompare = a.compareToIgnoreCase(b);
return stringCompare == 0 ? 1 : stringCompare; // returning 0 would merge keys
}
}
Upvotes: 3
Reputation: 109557
As the natural sort has nothing in common with your sorting wish:
List<Map.Entry<String, Integer>> entries = new ArrayList<>(m.entrieSet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer >a, Map.Entry<String, Integer>b) {
if (a.getValue() < b.getValue()) { // Descending values
return 1;
} else if (a.getValue() > b.getValue()) {
return -1;
}
return -a.getKey().compareTo(b.getKey()); // Descending keys
}
});
Upvotes: 3