1

I need to count how many of occurrences of a char in a string and print them in descending order. I can count chars in HashMap, but can't understand how to print map in descending order by values.

Something like this output:

String income = "abbccc";

Output:
c : 3
b : 2
a : 1
import java.util.*;

public class Main {
    public static void main(String[] args) {
        HashMap<Character, Integer> map = new HashMap<>();
        String income = "how are you?";

        int tmp;

        for (int i = 0; i < income.length(); i++) {
            if ( map.isEmpty() || !map.containsKey(income.charAt(i)) ) {
                map.put( income.charAt(i), 1 );
            } else if ( map.containsKey(income.charAt(i)) ) {
                tmp = map.get( income.charAt(i) );
                map.replace( income.charAt(i), ++tmp);
            }
        }

        for (Map.Entry<Character, Integer> mapTemp: map.entrySet()) {
            System.out.println(mapTemp.getKey() + " " + ":" + " " + mapTemp.getValue());
        }
}
}
Output:
  : 2
a : 1
r : 1
e : 1
u : 1
w : 1
h : 1
y : 1
o : 2
? : 1

Expected (needed) output:
  : 2
o : 2
a : 1
r : 1
e : 1
u : 1
w : 1
h : 1
y : 1
? : 1
Sankalpa Wijewickrama
  • 985
  • 3
  • 19
  • 30
Mike
  • 11
  • 1
  • 1
    [Sort a Map by values](https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values) – Abra Mar 31 '22 at 18:08
  • [TreeMap sort by value](https://stackoverflow.com/questions/2864840/treemap-sort-by-value) – Abra Mar 31 '22 at 18:10
  • 1
    It doesn't exist a native structure to sort by value. So you will have to code the sorting. This is discussed on this thread: https://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values . – Ernesto López Mar 31 '22 at 18:16
  • convert the entries into a stream, and use the comparator combinators from Map.Entry: Stream> sorted = map.entrySet().stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByValue())); – Leonard Klausmann Apr 01 '22 at 08:12

0 Answers0