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