Java统计一个字符串中各个字符出现的次数

相信很多人在工作的时候都会遇到这样一个,如何统计一个字符串中各个字符出现的次数呢,这种需求一把用在数据分析方面,比如根据特定的条件去查找某个字符出现的次数。那么如何实现呢,其实也很简单,下面我贴上代码:

public static void main(String[] args) {

        List<String> strs = new ArrayList<>();
        strs.add("123");
        strs.add("234");

        Map<Character,Integer> wordCount = new HashMap<Character,Integer>();
        for(String str:strs){
            for(int i=0;i<str.length();i++){
                if(wordCount.containsKey(str.charAt(i))){
                    wordCount.put(str.charAt(i),wordCount.get(str.charAt(i))+1);
                }else{
                    wordCount.put(str.charAt(i),1);
                }
            }
        }

        System.out.println(wordCount);
    }

有问题可以在下面评论,技术问题可以私聊我

原文地址:https://www.cnblogs.com/c1024/p/11012034.html