如何使用地图按字符串中出现的次数对字符进行排序? [英] How to sort a character by number of occurrences in a String using a Map?
问题描述
我编写了计算给定字符串中每个字符的频率并显示它的代码:
I wrote code that counts frequency of every character in a given string and displays it:
Map<Character, Integer> occurrences = new HashMap<>();
char[] chars = str2.toCharArray();
for (char character : chars) {
Integer integer = occurrences.get(character);
occurrences.put(character, integer);
if (integer == null) {
occurrences.put(character, 1);
} else {
occurrences.put(character, integer + 1);
}
}
System.out.println(occurrences);
现在,我想修改我的代码,因此它显示了按频率排列的字符.从字符开始,该字符最经常重复,然后第二次最频繁,然后第三次,依此类推.
Now I want to modify my code, so it shows the characters ordered by their frequency. Starting with the character, that is most frequently repeated, then second most frequently, then third and so on.
例如,字符串 Java
应该按以下顺序显示为字符频率: a = 2,j = 1,v = 1
.
For example the string Java
should be displayed as character-frequency in following order: a=2, j=1, v=1
.
推荐答案
If you use Java's TreeMap
implementation of the Map it will keep your values sorted by key.
There is also a constructor where you can pass a custom implementation of Comparator
if you need your way of sorting.
这篇关于如何使用地图按字符串中出现的次数对字符进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!