HashMap<Character, Integer> map = new HashMap<>();
String str = "eqweqwewqeewqdsadsadfasfhfdgas fsafdsf";
char c = str.charAt(0);
for (int i = 0; i < str.length(); i++) {
if (!map.containsKey(str.charAt(i))) {
map.put(str.charAt(i), 1);
} else {
map.put(str.charAt(i), map.get(str.charAt(i)) + 1);
}
}
// 使用比较器排序
ArrayList<Entry<Character, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<Character, Integer>>() {
@Override
public int compare(Entry<Character, Integer> o1, Entry<Character, Integer> o2) {
// o1-o2,从大到小,反之从小到大
return o2.getValue() - o1.getValue();
}
});
// 如果出现的最多的字符有很多个时,就遍历size(),如果只有一个就 i < 1
for (int i = 0; i < list.size(); i++) {
System.out.println("出现最多的数字:"+list.get(i)+"次");
}
统计字符串中出现最多的字符和出现的次数,对map的结果进行排序,使用了comparator方法
最新推荐文章于 2020-11-02 22:05:02 发布