HashMap案例_WordCount
给定一个字符串 "a,b,c,d,e,f,g,h,b,b,b,c,x,x,y,x,b"
写一个程序将这个字符串中的字母去重,将去重后的字母打印出来。
写一个程序统计出每一个字母出现的总次数,并将结果打印如下。
import java.util.HashMap; public class testWordCount2 { public static void main(String[] args) { // 输入字符的分割 String str = "a,b,c,d,e,f,g,h,b,b,b,c,x,x,y,x,b"; String[] words = str.split(","); System.out.println("str数组的大小为:"+words.length); // 思路:定义一个HashMap,遍历数组,如果HashMap中没有数组的元素,则input一个元素,如果HashMap中已经有了该key, // 则将该key对应的value+1。 HashMap<String, Integer> intMap = new HashMap<String, Integer>(); // 遍历数组,进行逻辑判断 for(String word: words) { if(intMap.containsKey(word)) { intMap.put(word,intMap.get(word)+1); }else { intMap.put(word,1); } } // 打印去重的结果 for(String s: intMap.keySet()) { System.out.println(s); } // 打印统计结果 for(String s: intMap.keySet()) { System.out.println(s+":"+intMap.get(s)); } } }