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
How to Sort a TreeMap By Value in Java? In Java Language, a TreeMap always stores key-value pairs which are in sorted order on the basis of the key. TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap contains unique keys. The elements in TreeMap are sorted on the basis of keys.
In Java Language, a TreeMap always stores key-value pairs which are in sorted order on the basis of the key. TreeMap implements the NavigableMap interface and extends AbstractMap class. TreeMap contains unique keys.
However, the insertion order is not retained in the TreeMap. Internally, for every element, the keys are compared and sorted in ascending order. After adding the elements if we wish to change the element, it can be done by again adding the element with the put () method.
The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. This proves to be an efficient way of sorting and storing the key-value pairs.
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
}
}
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With