6

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
Katie
  • 3,517
  • 11
  • 36
  • 49

2 Answers2

3

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
    }
}
assylias
  • 321,522
  • 82
  • 660
  • 783
3

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
    }    
});
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • +1. It is an astoundingly bad idea to try to write a comparator by value like the OP is doing, and will doom your code to confusing, surprising, and impossible-to-debug messes. – Louis Wasserman Feb 01 '13 at 16:48