当前位置: 移动技术网 > IT编程>开发语言>Java > 统计字符串中每个字符的个数

统计字符串中每个字符的个数

2020年07月18日  | 移动技术网IT编程  | 我要评论

思路:将字符串转换为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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网