【Map】获取字符串中,每一个字母出现的次数

 1 package cn.itcast.p1.map.test;
 2 
 3 import java.util.Iterator;
 4 import java.util.Map;
 5 import java.util.TreeMap;
 6 /*练习:
 7  *   打印结果:a(1) b(2) c(3)...
 8  * 思路:
 9  * 对于结果的分析发现,字母和次数之间存在着映射的关系。而且这种关系好多。
10  * 好多酒需要存储,能存储映射关系的容器有数组和Map集合。
11  * 关系一方是有序编号吗? 没有
12  * 那就是使用Map集合。又发现可以保证唯一性的一方的一方具备着顺序如a b c。。。
13  * 所以可以使用TreeMap集合。
14  * 
15  * 这个集合最终应该存储的是字母和次数的对应关系。
16  * 
17  * 1.因为操作的是字符串中的字母,所以先将字符串变成字符数组。
18  * 2.遍历字符数组,用每一个字母作为键去查Map集合这个表。
19  * 如果字母键不存在,就将该字母作为键,1作为值存储到map集合中
20  * 如果该字母键存在,就将该字母键对应值取出并+1,在将该字母和+1后的值存储到map集合中
21  * 键相同,值会覆盖。这样就记录住了该字母的次数
22  * 
23  * 3.遍历结束。map集合就记录所有字母的出现次数。
24  * 
25  */
26 
27 public class Maptest {
28 
29     public static void main(String[] args) {
30         String str = "fdgavAde   bs5dDadfgjkdgasxbccxvvcxn1bnb-dfs";
31         
32         String s = getCharCount(str);
33         
34         System.out.println(s);
35 
36     }
37 
38     private static String getCharCount(String str) {
39         //将字符串转化成字符数组
40         char[] chs = str.toCharArray();
41         //定义map集合表
42         Map<Character,Integer> map = new TreeMap<Character,Integer>();
43         
44         for(int i=0; i<chs.length; i++)
45         {
46 //            if (!(chs[i]>='a' && chs[i]<='z'  ||  chs[i]>='A' && chs[i] <='Z'))
47             if (!(Character.toLowerCase(chs[i])>='a' && Character.toLowerCase(chs[i])<='z'))
48                 continue;
49             
50             //将数组中的字母作为键去查map表。
51             Integer value = map.get(chs[i]);
52             
53             int count = 1;
54             
55             if(value!=null)
56             {
57                 count = value+1;
58             }
59             
6061             
62             map.put(chs[i], count);
63         }
64         
65         return mapToString(map);
66     }
67 
68     private static String mapToString(Map<Character, Integer> map) {
69         StringBuilder sb = new StringBuilder();
70         
71         Iterator<Character> it = map.keySet().iterator();
72         
73         while(it.hasNext())
74         {
75             Character key = it.next();
76             Integer value = map.get(key);
77             sb.append(key+"("+value+")"+" ");
78         }
79         
80         return sb.toString();
81         
82     }
83 
84 }

原文地址:https://www.cnblogs.com/Newbie-Cai/p/5814258.html