Map集合練習:
"asfefxAAcf34vrfdfse2-2asd--wdd"獲取該字符串中,每一個字母出現的次數
要求打印的結果是:a(2)c(1)...;
思路:
對結果分析發現,結果中字母和出現次數之間構成映射關系,而且很多,
很多就需要存儲。能存儲映射關系的有數組和Map集合。
關系中有一方順序固定么?沒有,所以選有Map集合。
又發現可以作為唯一標識的一方有自然順序,即字母表的順序;
所以選有TreeMap存儲。
集合中最終存儲的是以字母為鍵,以字母出現次數為值的映射關系。
1.因為操作的是字符,所以先把字符串轉化成字符數組。
2.遍歷字符數組,分別以字母為鍵去Map集合中判斷,集合中是否包含該元素,
如果不包含,則以該字母為鍵,以1為值,存入Map集合中;
如果包含,則取出該字母對應的值,加一,再把該字母和新的值存入集合,這樣新的值就會覆蓋舊的值。
3.遍歷完畢,每個字母對應的值便是其在該字符串中出現的次數,
在對集合進行打印輸出即可。
1 public class MapTest { 2 3 public static void main(String[] args) { 4 String str="asfefxAAcf34vrfdfse2-2asd--wdd"; 5 String s=countChar(str); 6 System.out.println(s); 7 8 } 9 //定義實現統計字母出現次數的靜態方法 10 public static String countChar(String str) { 11 char[] chs=str.toCharArray(); 12 Map<Character,Integer> tm=new TreeMap<Character,Integer>(); 13 for (int i = 0; i < chs.length; i++) { 14 //只統計字母出現次數,不統計其他字符 15 if(!(chs[i]>='a' && chs[i]<='z'|| chs[i]>='A' && chs[i]<='Z')) 16 continue; 17 int count=1; 18 Integer value=tm.get(chs[i]); 19 if(value!=null) 20 count+=value; 21 tm.put(chs[i], count); 22 23 } 24 return printMap(tm); 25 } 26 //定義按規格打印集合的方法 27 private static String printMap(Map<Character, Integer> tm) { 28 StringBuilder sb=new StringBuilder(); 29 Iterator<Character> it=tm.keySet().iterator(); 30 while(it.hasNext()) 31 { 32 Character key=it.next(); 33 Integer value=tm.get(key); 34 sb.append(key+"("+value+") "); 35 } 36 return sb.toString(); 37 } 38 }