How to sort TreeMap <String, Integer>?
I have a map: TreeMap<String, Integer> m = new TreeMap<>(); where I have the whole alphabet and meanings that show how many times each letter has been found in my text.
I want to sort this card in descending order; that is, the most frequent letter is in the first line, and the last line of output indicates the least frequent letter. If two letters have the same frequency, then the first letter in the alphabet should appear. How to do it?
I tried with the 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 the way out:
D 3 E 3 A 2 S 5 Guys ... Found this before, it didn't help at all. Good performance should be:
S 5 D 3 E 3 A 2 +6
2 answers
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 } } +3
Since a natural variety has nothing to do with your desire for sorting:
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 } }); +3