思路:将字符串转换为char数组,利用HashMap的特性来计算重复字符的个数
public static void main(String[] args) {
String str = "abbcccfggfydddd";
countChar(str);
}
public static void countChar(String str) {
Map<Character, Integer> map = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
//获取字符串中的单个字符
Character c = str.charAt(i);
//判断该字符是否已存在
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
//存在,则数量加1
map.put(c, map.get(c) + 1);
}
}
map.forEach((k, v) -> {
System.out.println(k + ":" + v);
});
//将Map存入List,然后根据数量排序
List<Map.Entry<Character, Integer>> list = new ArrayList<>();
list.addAll(map.entrySet());
Collections.sort(list,Comparator.comparing(o -> o.getValue())); //默认升序
//Collections.sort(list, (o1, o2) -> o2.getValue() - o1.getValue()); //重写比较器,降序排列
list.forEach(System.out::println);
}
//输出结果:
a:1
b:2
c:3
d:4
f:2
g:2
y:1
a=1
y=1
b=2
f=2
g=2
c=3
d=4
本文地址:https://blog.csdn.net/MDW12345/article/details/107411670
如对本文有疑问, 点击进行留言回复!!
Algebra:Chapter 0 - 预备知识: 集合论和categories
springboot + vue上传图片在服务器并实现在线预览
请谨慎使用增强for循环,刚接触Java值得一看(手动狗头)
【Nginx】还不会使用Nginx解决跨域问题?肝这一篇就够了!!
网友评论