相信很多人在工作的時候都會遇到這樣一個,如何統計一個字符串中各個字符出現的次數呢,這種需求一把用在數據分析方面,比如根據特定的條件去查找某個字符出現的次數。那么如何實現呢,其實也很簡單,下面我貼上代碼:
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);
}
有問題可以在下面評論,技術問題可以私聊我
